首页 > 解决方案 > Gson 不映射 Java 中的值

问题描述

我从 API 得到这个结果:

{"sessionID":"","randomKey":"","id":0,"userName":"","useIPAddress":"","usePortNo":"","response":{"code":-24,"message":"Incorrect credential","postedDateTime":null,"accountNo":0,"trxnNo":0,"changeTypeID":0}}

我的课是这样的:

class ResponseLoginParam {
    val RandomKey: String? = null
    val SessionID: String? = null
    val UseIPAddress: String? = null
    val UsePortNo: Int? = null
    val UserName: String? = null
    val Response: Response? = Response()
}

class Response {
    val Code: Int? = null
    val Message: String? = null
    val PostedDateTime: String? = null
    val AccountNo: Int? = null
    val ChangeTypeID: Int? = null
}

由于某种原因,它没有映射到我的对象。但如果我得到这样的结果:

{"SessionID":"","RandomKey":"","Id":0,"UserName":"","UseIPAddress":"","UsePortNo":"","Response":{"Code":-24,"Message":"Incorrect credential","PostedDateTime":null,"AccountNo":0,"TrxnNo":0,"ChangeTypeID":0}}

它现在大写,我可以正确映射值。为什么是这样?

标签: javakotlingson

解决方案


您需要同样命名类和 json 字段,或者定义序列化名称:

  class Response {
    @SerializedName("code") // since its "code" in json
    val Code: Int? = null
    //no need for annotation because class field name equals json field name
    val message: String? = null
   }

推荐阅读