自定义序列化器
方式1-局部注册
@Data
public class AssetDTO {
private String assetCode;
private String city;
private String assetPackageName;
@JsonSerialize(using = ListJsonSerializer.class)
private List<AssetTypeMethod> valuationMethods;
@JsonDeserialize(using = BigDecimalJsonDeserializer.class)
private BigDecimal adjustOfSpecialUse;
// 反序列化的时候对集合进行降序排序
public void setValuationMethods(List<AssetTypeMethod> valuationMethods) {
// valuationMethods.sort(Comparator.comparingInt(AssetTypeMethod::getRecommendPriority));
valuationMethods.sort(((o1, o2) -> o2.getRecommendPriority() - o1.getRecommendPriority()));
this.valuationMethods = valuationMethods;
}
}
@Data
public class AssetTypeMethod {
private String assetTypeCode;
private Long methodId;
private String methodName;
private Integer recommendPriority;
}
方式2-全局注册
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
protected ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 设置Date类型字段序列化方式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE));
// 注册转换器
SimpleModule simpleModule = new SimpleModule();
// 指定 BigDecimal类型 字段使用自定义的 BigDecimalJsonDeserializer 序列化器
simpleModule.addDeserializer(BigDecimal.class, new BigDecimalJsonDeserializer());
simpleModule.addSerializer(List.class, new ListJsonSerializer());
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
自定义序列化器
序列化时对List 进行排序
public class ListJsonSerializer extends JsonSerializer<List<AssetTypeMethod>> {
@Override
public void serialize(List<AssetTypeMethod> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
} else {
value.sort(((o1, o2) -> o2.getRecommendPriority() - o1.getRecommendPriority()));
gen.writeObject(value);
}
}
}
序列化: Java Bean 对象转 Json字符串
反序列化时对BigDecimal进行保留三位小数
public class BigDecimalJsonDeserializer extends JsonDeserializer<BigDecimal> {
@Override
public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
double value = p.getValueAsDouble();
return new BigDecimal(value).setScale(3, BigDecimal.ROUND_HALF_UP);
}
}
反序列化: Json字符串 转 Java Bean 对象