如何在Kotlin中使用Gson反序列化嵌套类



我有json,如下所示,我对kotlin非常陌生,我尝试了所有的例子,但在转换为json 时无法设置嵌套类的值

这里是我的json

{"Init":{"MOP":[{"Id":"1","Type":"0","ProtocolVersion":"1.0","MopCode":"*NEXB","TerminalId":"'P400Plus-275008565'","IP":"'192.168.1.15'","Currency":"EUR"},{"Id":"2","Type":"0","ProtocolVersion":"1.0","MopCode":"*NEXF","TerminalId":"'P400Plus-275008565'","IP":"'10.0.0.0:901'","Currency":"EUR"}]}}

这是我的POJO

class Root {
@JsonProperty("Init")
var init: Init? = null
}
class MOP {
@JsonProperty("Id")
var id: String? = null
@JsonProperty("Type")
var type: String? = null
@JsonProperty("ProtocolVersion")
var protocolVersion: String? = null
@JsonProperty("MopCode")
var mopCode: String? = null
@JsonProperty("TerminalId")
var terminalId: String? = null
@JsonProperty("IP")
var ip: String? = null
@JsonProperty("Currency")
var currency: String? = null
}
class Init {
@JsonProperty("MOP")
var mop: List<MOP>? = null
}

这是我的试用

val root: TestClass.Root = gson.fromJson(receiveString,TestClass.Root::class.java)
val initList = HashMap<String?,String?>()
if (root.init != null){
val mopList = root.init!!.mop
if (mopList != null) {
for (item in mopList){
initList.put(item.mopCode,item.id)
}
}
}

root.initroot.init.mop始终为空

你能给我什么建议?

感谢

Json构造有不同的树。

您应该使用以下结构:

data class Root (
@SerializedName("Init") val init : Init
)
data class Init (
@SerializedName("MOP") val mOP : List<MOP>
)
data class MOP (
@SerializedName("Id") val id : Int,
@SerializedName("Type") val type : Int,
@SerializedName("ProtocolVersion") val protocolVersion : Double,
@SerializedName("MopCode") val mopCode : String,
@SerializedName("TerminalId") val terminalId : String,
@SerializedName("IP") val iP : String,
@SerializedName("Currency") val currency : String
)

你可以用进行解析

Gson().fromJson(data,Root::class.java)

此外,如果您使用的是Gson,则应该使用SerializedName而不是JsonProperty

最新更新