为什么 @JsonProperty 不适用于 Kotlin 中的驼峰式大小写属性

Why @JsonProperty not work for camel case properties in Kotlin

有个很简单的class:

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}

而如果把yprice的属性改成yPrice,那么结果就变成:

{"yprice":null,"zprice":null}

@JsonProperty 似乎不适用于驼峰式大小写属性。

您需要指示 ObjectMapper 基于字段而不是基于 getter 方法生成 JSON 属性。您可以使用 com.fasterxml.jackson.annotation.JsonAutoDetect 注释:

@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY)
class Price(

从现在开始,在所有情况下您都应该看到相同的结果。

看看:

  • Jackson/Hibernate, meta get methods and serialization
  • How to ignore "Is' methods with Jackson 2.2.3