Justin
09/08/2019, 9:08 PMkotlinx.serialization
in a multplatform project.
The basic question is this: what is the best way to handle deserialization of Json when one of the field names (i.e. keys) is variable?
I have put together a simple example to illustrate the problem:
@Serializable data class UserData(val name: String)
@Serializable
data class User(
val user_data: UserData,
val user_contributions: List<Contribution>
) {}
interface Action {
val id: String
}
@Polymorphic interface Content
@Polymorphic interface Contribution : Action {
val content: Content
}
@Serializable data class Mentor(
override val id: String,
@SerialName("mentorContent")
override val content: MentorContent
) : Contribution {
@Serializable data class MentorContent(val mentor: String, val mentee: String) : Content
}
@Serializable data class Judge(
override val id: String,
@SerialName("judgeContent")
override val content: JudgeContent
) : Contribution {
@Serializable data class JudgeContent(val judge: String, val judged: String) : Content
}
// Given this JSON:
{
"user_data": {
"name": "Justin"
},
"user_contributions": [
{
"id": "1",
"mentorContent": {
"mentor": "Lisa",
"mentee": "Phil"
}
},
{
"id": "2",
"judgeContent": {
"judge": "Robert",
"judged": "Karen"
}
}
]
}
// This is the desired deserialized object:
User(
user_data = UserData(name = "Justin"),
user_contributions = listOf(
Mentor(
id = "1",
content = MentorContent(mentor = "Lisa", mentee = "Phil")
),
Judge(
id = "2",
content = JudgeContent(judge = "Robert", judged = "Karen")
)
)
)
Fudge
09/08/2019, 10:24 PM@polymorphic
afaik
2. Can the content
of user_contributions
be anything? or is it just a finite set of keysFudge
09/08/2019, 10:27 PMJustin
09/08/2019, 10:46 PMJustin
09/08/2019, 10:47 PMcontent
propertyJustin
09/08/2019, 10:49 PMFudge
09/08/2019, 11:18 PMid
. With no id
you could do user_contributions: Map<String,Map<String,String>>
Fudge
09/08/2019, 11:31 PMJustin
09/08/2019, 11:40 PMuser_contributions
into a generic map; it must to be serialized into a list of type Contribution
(hence all the types I wrote out).molikuner
09/09/2019, 7:39 AMContribution
) Downside: You need to repeat all the possible types.Justin
09/09/2019, 3:28 PMmolikuner
09/09/2019, 4:41 PMwhen
statement.