java - 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}}
它现在大写,我可以正确映射值。为什么是这样?
解决方案
您需要同样命名类和 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
}
推荐阅读
- javascript - 如何在 JS 中存储点击事件的一些数据?
- javascript - react native 如何根据条件在不同组件之间导航
- reactjs - 尝试使用 export * 语法时 ESLint、React/TS 出现问题
- angular - Angular 的动态 base-href
- python - 无法在 Python 中读取和加载 JSON 文件,JSON 格式不同
- python - 检查点是否在点列表中的高效方法
- c# - 如何为输入字段赋值?
- php - Yii2 Active Query的“选择操作”中可以调用反序列化函数吗
- ios - 问题 ITMS-90809:Firebase 项目中已弃用的 API 使用(Cordova 插件)
- apache-kafka - 为什么我的消费者控制台不与我的文本文件同步?