天天看点

ObjectMapper @JsonProperty 不生效问题处理(kotlin)

一、问题阐述:

在日常开发中,因为公司业务需求,需要将驼峰格式的属性转换为全大写,但是使用了ObjectMapper后,发现 @JsonProperty 好像不能实现这个功能

有一个非常简单的类:

class Price(
    @JsonProperty("YPRICE")
    val yprice: String? = null,

    @JsonProperty("ZPRICE")
    val zPrice: String? = null
)
           

把这个类序列化成字符串

val mapper = ObjectMapper().registerKotlinModule()
mapper.writeValue(System.out, Price())
           

控制台中的结果是:

{"YPRICE":null,"zprice":null}
           

如果把属性 zPrice 修改为 zprice,则结果更改为:

{"YPRICE":null,"ZPRICE":null}
           

二、解决方法

在类上添加 com.fasterxml.jackson.annotation.JsonAutoDetect 注解

@JsonAutoDetect(getterVisibility = NONE, fieldVisibility = ANY)
class Price(
    @JsonProperty("YPRICE")
    val yprice: String? = null,

    @JsonProperty("ZPRICE")
    val zPrice: String? = null
)