Jackson 自定義序列化器

自定義序列化器

方式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 對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章