Retrofit或Jackson ObjectMapper将"aId"属性映射为小写的"aid"。

8
我正在使用 Jackson 2.9.2Retrofit 2.1.0 进行一些 POST 操作,其中一个 JSONArray 作为 HTML-Header 参数。
API 定义了一个名为 aId 的值。无论我尝试什么,我的 JSON 属性 总是被转换为小写(aid)。
我用 abId 测试了我的相同代码,并且它可以工作... 有人知道我的配置错在哪里或者哪个约定反对这个属性名吗?
//ObjectMapper initialization
ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)


//the data class
import com.fasterxml.jackson.annotation.JsonProperty

data class MyClass(
    @JsonProperty
    val aId: String? = null, //<-- not working
    @JsonProperty
    val abId: String? = null //working!
)

//Retrofit call 
import retrofit2.http.Body

@POST("log")
fun sendLog(@Body logs: List<MyClass>): Call<MyCall>

//JSON Result in HTML Header
[{  
  "aid":"some_value",  //should be "aId"
  "abId":"some_value"  //is correct
 }]

我尝试使用以下注释:
  • @SerializedName("aId")

  • @JsonProperty("aId")

  • @JsonRawValue

  • @JsonAlias


1
尝试查看有关Kotlin数据类使用Jackson @JsonProperty注释的用法:https://dev59.com/M1YN5IYBdhLWcg3wFkwL - Michał Ziober
@MichałZiober 谢谢老兄,这就解决了!请将此作为答案发布以获取赏金点数。 - longi
1
我不确定是否应该因为链接到另一个很好的答案而接收它们。StackOverflow 不喜欢重复的答案,所以我认为有些管理员应该将您的问题标记为重复,并指向链接的问题/答案。如果你真的想要感谢我,请给我一些与 JacksonJSON 相关的答案点赞,如果你认为它们值得的话。 - Michał Ziober
2个回答

2

Try this @get:JsonProperty("aId")


抱歉,我没有查看上面的评论。我在我的项目中遇到了同样的问题,所以我已经知道答案了。 - Amroun

2
请参考Michael Ziober发布的链接Jackson @JsonProperty注释在Kotlin数据类中的用法
描述的问题是由于Jackson默认不扫描私有字段导致的。可以使用@JsonAutoDetect更改此行为。
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
data class MyClass(
   @JsonProperty
   val aId: String? = null, 
   @JsonProperty
   val abId: String? = null 
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接