Skip to content

Instantly share code, notes, and snippets.

@JUSTINMKAUFMAN
Last active September 9, 2019 01:26
Show Gist options
  • Save JUSTINMKAUFMAN/510db77af727d6c80728ec7daa68cf2d to your computer and use it in GitHub Desktop.
Save JUSTINMKAUFMAN/510db77af727d6c80728ec7daa68cf2d to your computer and use it in GitHub Desktop.
Kotlinx Serialization with Variable Fields
// What is the best way to handle deserialization of JSON
// when one of the fields can be encoded with any of
// several different names (e.g. 'judgeContent and
// 'mentorContent', which all deserialize to the
// `Contribution.content` property of `User.user_contributions`)?
@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")
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment