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 对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jaemon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值