【问题标题】:Deserialize complex JSON in Kotlin在 Kotlin 中反序列化复杂的 JSON
【发布时间】:2022-07-29 18:48:18
【问题描述】:

我想反序列化以下 JSON:

{
    "participants": {
        "0": {
            "layout": "layout1"
        }
    },
    "layouts": {
        "layout1": {
            "width": 100,
            "height": 100
        }
    }
}

进入如下结构:

@Serializable
data class Layout(val width: Int, val height: Int)

@Serializable
data class Participant(val index: Int, val layout: Layout)

@Serializable
data class ViewData(val participants: MutableMap<Int, Participant>, val layouts: MutableMap<Int, Layout>)

我特别苦恼的是如何使用“布局”哈希中的“布局1”键在参与者的布局之间创建正确的关系。

谢谢!

【问题讨论】:

  • 你到底想做什么?不幸的是,我不明白:(
  • 想将我的数据从 json 转换成上面的类

标签: json kotlin deserialization kotlin-serialization


【解决方案1】:

你必须创建匹配 json 字符串的类

        data class Layout(
            val width: Int,
            val height: Int
        )

        data class Participant(
            val layout: String
        )

        data class ViewData(
            val participants: Map<String, Participant>,
            val layouts: Map<String, Layout>
        )

然后创建一个函数,帮助您按参与者姓名获取布局

        data class ViewData(
            val participants: Map<String, Participant>,
            val layouts: Map<String, Layout>
        ) {

            fun getLayoutForParticipant(participantId: String): Layout? {
                val layoutId = participants[participantId]?.layout
                return layoutId?.let { layouts[it] }
            }
        }


        val json: String = """
            {
                "participants": {
                    "0": {
                        "layout": "layout1"
                    }
                },
                "layouts": {
                    "layout1": {
                        "width": 100,
                        "height": 100
                    }
                }
            }

        """

        val deserialized: ViewData = objectMapper.readValue(json, ViewData::class.java)

        println(deserialized)
        println(deserialized.getLayoutForParticipant("0"))

结果:

ViewData(participants={0=Participant(layout=layout1)}, layouts={layout1=Layout(width=100, height=100)})
Layout(width=100, height=100)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2019-04-29
    相关资源
    最近更新 更多