Sebastian Schuberth
07/12/2023, 2:42 PMversion
field in a header
section. At first I though I could use a sealed class
instance per version and https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#class-discriminator-for-polymorphism, but the problem is that the "discriminator" in this case is the version
that is part of a different JSON hierarchy than the changing structures themselves. Is there a way to solve this with built-in means / annotations instead of going the route of manually writing custom deserializers?Adam S
07/12/2023, 2:45 PMSebastian Schuberth
07/12/2023, 2:47 PM{
"headers": [
{
"output_format_version": "2.0.0"
}
],
"files": [
{
// Different structure based on "output_format_version" above.
}
]
}
Sebastian Schuberth
07/12/2023, 2:47 PMSebastian Schuberth
07/12/2023, 2:51 PMJsonElement
I'm deserializing.Adam S
07/12/2023, 2:53 PMSebastian Schuberth
07/12/2023, 2:55 PMJsonElement
, in order to access the header from here again...Adam S
07/12/2023, 2:57 PM@Serializable(with = SomeContentBasedSerializerForMyJsonContent::class)
sealed interface MyJsonContent {
val files: List<FileType>
class Version1 {
val headers: List<>,
override val files: List<FileTypeV1>,
}
class Version2 {
val headers: List<>,
override val files: List<FileTypeV2>,
}
class Version3 {
val headers: List<>,
override val files: List<FileTypeV3>,
}
}
sealed interface FileType // just here for organisation, doesn't need to be @Serializable
class FileTypeV1 (....): FileType
class FileTypeV2 (....): FileType
class FileTypeV3 (....): FileType
Adam S
07/12/2023, 3:25 PMval files: List<JsonObject>
, and then ‘properly’ decode them once the containing object (and the headers) are decoded. This would be nicer because there’s no custom serializers needed.Sebastian Schuberth
07/12/2023, 3:27 PMdata class
based decoding with JsonObject
decoding...Adam S
07/12/2023, 3:28 PMSebastian Schuberth
07/12/2023, 3:31 PMAdam S
07/12/2023, 3:34 PMSebastian Schuberth
07/12/2023, 3:35 PMSebastian Schuberth
07/12/2023, 3:48 PMSerializersModule
at runtime depending on the output_format_version
... I'll experiment with that.