简体   繁体   English

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

[英]How to deserialize nested class with Gson in Kotlin?

I have json as in below, I'm really new on kotlin and i tried all examples but cannot set my nested class values when i convert to json我有下面的 json,我真的是 kotlin 的新手,我尝试了所有示例,但在转换为 json 时无法设置嵌套类值

Here my 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"}]}}

Here my POJO这是我的 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
 }

Here my trial这是我的审判

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)
                }
            }

        }

Always root.init and root.init.mop are null始终root.initroot.init.mop为空

What you can suggest me?你能给我什么建议?

Thanks谢谢

Your Json construction has different tree.你的 Json 构造有不同的树。

You should use following structure:您应该使用以下结构:

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
)

And you can parse just with:你可以解析:

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

Also if you are using Gson, you should use SerializedName instead JsonProperty .此外,如果您使用 Gson,则应使用SerializedName而不是JsonProperty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM