天天看點

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
)