【问题标题】:How to deserialize nested class with Gson in Kotlin?如何在 Kotlin 中使用 Gson 反序列化嵌套类?
【发布时间】:2020-11-16 15:37:17
【问题描述】:

我有 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 始终为空

你能给我什么建议?

谢谢

【问题讨论】:

    标签: java android json kotlin


    【解决方案1】:

    你的 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

    【讨论】:

    • @Ibasek 如何创建这个结构?你用过什么网站吗?
    • 作为一名程序员,您应该能够创建自己(这很容易但有时很糟糕),但是有一些工具可以生成它:json2kotlin.com 和 AS 插件 JsonToKotlinClass
    • 你是对的,但不幸的是,当你与时间抗争时,这些东西会很有用......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多