0

I would like to deserialize the following JSON:

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

Into the following structure:

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

What I'm particularly struggling with is how to create the correct relationship between participant's layout using the key "layout1" in the "layouts" hash.

Thanks!

aSemy
  • 5,485
  • 2
  • 25
  • 51
Nahum Bazes
  • 610
  • 1
  • 6
  • 15

1 Answers1

0

You have to create the classes that matches the json string

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

It is not possible (by default) to deserialize map<String, Any> to map<Int, Any> and it is not possible to add magical val index: Int

then create a function that will help you get layout by participant name

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

result:

ViewData(participants={0=Participant(layout=layout1)}, layouts={layout1=Layout(width=100, height=100)})
Layout(width=100, height=100)
Mateusz
  • 690
  • 1
  • 6
  • 21
  • Thank you very much for this. I was thinking about some sort of a custom serializer. Is this possible somehow? – Nahum Bazes Jul 29 '22 at 12:44
  • yup, it is possible, but depends on what deserializer you use. But I'm not sure that it is a better or simpler way – Mateusz Jul 29 '22 at 16:39
  • Mateusz, what is the objectMapper you are using? Is it standard in Kotlin? Can it be used in MKP? – Nahum Bazes Jul 30 '22 at 08:30