1.全局配置类
@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
JsonFactory jsonFactory =
new JsonFactoryBuilder().enable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS).build();
ObjectMapper objectMapper = builder.createXmlMapper(false).factory(jsonFactory).build();
SimpleModule module = new SimpleModule();
module.addSerializer(Sort.class, new SortJsonComponent.SortSerializer());
module.addDeserializer(Sort.class, new SortJsonComponent.SortDeserializer());
module.addSerializer(Instant.class, InstantJsonSerializer.INSTANCE);
module.addDeserializer(Instant.class, InstantJsonDeserializer.INSTANCE);
module.addSerializer(BigDecimal.class, bigDecimalJsonSerializer());
objectMapper.registerModules(new PageJacksonModule(), module);
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
return objectMapper;
}
2.Instant序列化
public class InstantJsonSerializer extends JsonSerializer<Instant> {
public static final InstantJsonSerializer INSTANCE = new InstantJsonSerializer();
@Override
public void serialize(
Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeNumber(instant.toEpochMilli());
}
}
3.Instant反序列化
public class InstantJsonDeserializer extends JsonDeserializer<Instant> {
public static final InstantJsonDeserializer INSTANCE = new InstantJsonDeserializer();
@Override
public Instant deserialize(JsonParser jsonParser, DeserializationContext
deserializationContext)
throws IOException {
return Instant.ofEpochMilli(jsonParser.getLongValue());
}
}
4.Bigdecimal 去掉多位数多余的零
public JsonSerializer<BigDecimal> bigDecimalJsonSerializer() {
return new JsonSerializer<BigDecimal>() {
@Override
public void serialize(
BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
if (!ObjectUtils.isEmpty(bigDecimal)) {
jsonGenerator.writeNumber(bigDecimal.stripTrailingZeros());
}
}
};
}
该文章展示了如何在Java中自定义Jackson配置,包括创建一个主ObjectMapper实例,用于XML解析,以及注册模块来处理Instant和BigDecimal的序列化与反序列化,确保数值精确无误。Instant序列化为Unix时间戳,反序列化则从长整型恢复,BigDecimal序列化时会去掉多余的零。
628

被折叠的 条评论
为什么被折叠?



