Gson在Java中不映射值

Gson在Java中不映射值,java,kotlin,gson,Java,Kotlin,Gson,我从一个API中得到这个结果: {"sessionID":"","randomKey":"","id":0,"userName":"","useIPAddress":"","usePortNo":"","response":{"code":

我从一个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}}

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

您需要对类和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
   }

使用GsonBuilder创建Gson对象时,请将字段命名策略设置为
GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER\u CAMEL\u CASE)
。是否可以添加特定于使用Gson获取API响应并映射到类的代码?Hi Ibanez1408。为了提高问题的简洁性和可读性,我对你的一些问题进行了编辑。他们往往反映出一种恳求、奉承的语气,读者可能会觉得这是强迫性的——记住他们是志愿者。我能请你坚持技术写作吗?你写这篇文章不仅仅是为了解决眼前的问题,也是为了帮助许多未来的读者创造一个问答。