Emil Orvik Kollstrøm
07/29/2020, 5:29 AM{
"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:
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.andylamax
07/29/2020, 5:43 AMEmil Orvik Kollstrøm
07/29/2020, 6:59 AMsikri
07/29/2020, 7:26 AMEmil Orvik Kollstrøm
07/29/2020, 7:30 AMimport 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)
}