【问题标题】:Retrofit or Jackson ObjectMapper maps "aId" property to lowercase "aid"Retrofit 或 Jackson ObjectMapper 将“aId”属性映射为小写“aid”
【发布时间】:2019-11-25 05:54:29
【问题描述】:

我使用Jackson 2.9.2Retrofit 2.1.0 进行一些POST 操作,JSONArray 作为HTML-Header 参数。

API 定义了一个值为aId。无论我尝试什么,我的 JSON property总是 转换为小写 (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

【问题讨论】:

  • @MichałZiober 谢谢老兄,成功了!将此作为答案发布以获取赏金
  • 我不确定,我应该收到它们以链接到另一个很好的答案。 StackOverflow 不喜欢重复的答案,所以,我认为,一些管理员应该将您的问题标记为重复并指向链接的问题/答案。如果您真的想感谢我,请支持我与JacksonJSON 相关的一些答案,当然如果您认为他们应得的。

标签: android json jackson retrofit


【解决方案1】:

试试这个@get:JsonProperty("aId")

【讨论】:

  • 抱歉,我没有检查上面的 cmets。我在我的项目中遇到了同样的问题,所以我已经知道答案了。
【解决方案2】:

请参阅 Michael Ziober 发布的答案链接Usage of Jackson @JsonProperty annotation for kotlin data classes

所描述的问题是Jackson's 默认行为不扫描私有字段的结果。可以使用@JsonAutoDetect 更改此行为

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
data class MyClass(
   @JsonProperty
   val aId: String? = null, 
   @JsonProperty
   val abId: String? = null 
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多