How would you guys go about deserializing JSON obj...
# serialization
e
How would you guys go about deserializing JSON objects that work like maps, where the properties are keys? For instance if you have something like this:
Copy code
{
  "thread": {
    "name": "Kotlin serialization question",
    "messages": {
      "xSDkj3402": {
        "text": "How would you guys..."
        "author" "kollstrom"
      }, 
      "-3krdjdfs03": {
        "text": "I see! The solution to all of your problems is..."
        "author": "helpful_person"
      }
    }
  }
}
Since the objects in “messages” in fact work like a map, how do you deserialize this into:
Copy code
data class Thread(
  val name: String,
  val messages: Map<String, Message>
)

data class Message(
  val text: String,
  val author: String
)
Now I know how to deserialize top-level objects into a map, but whenever I try to do the same thing on lower-level objects I always get strange behavior it seems. I’ve tinkered the most with Jackson, but open to #klaxon, kotlinx.serialization, Gson or whatever library that could make something like this work. Am I thinking about this weirdly? Is it easier if I don’t use maps but a class called Messages? I’ve tried that too, but still getting weird errors or not getting it to work correctly while going down that path, so very welcome to ideas.
a
I am almost certain that this works with kotlinx serialization
3
🙇‍♂️ 1
e
Any tips on resources with how to do this?
s
doesn’t it work like that just out of the box?
e
Yes, just got around to test it. For future reference this is what I did to test this:
Copy code
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import java.io.File

@Serializable
data class Thread(
        val name: String,
        val messages: Map<String, Message>
)

@Serializable
data class Message(
        val text: String,
        val author: String
)

fun main() {
    val jsonString: String = File("./src/main/resources/thread.json").readText(Charsets.UTF_8)
    val json = Json(JsonConfiguration.Stable)
    val deserialized = json.parse(Thread.serializer(), jsonString)
}