Jesse Hill
08/17/2021, 7:23 PMJesse Hill
08/17/2021, 7:23 PM{
"data": [
{
"id": "thing1",
"someArrayOfItems": ["one", "two"],
"other": [...SpecialType]
},
{
"id": "thing2",
"some-array-of-items": ["four", "five"],
"other": [...SpecialType]
}
]
}
The output that I would like to achieve would be:
@Serializable
data class Things(
val id: String,
val someArrayOfItems: Array<String>,
val other: List<SpecialType>
)
@Serializable
data class SpecialType(
val name: String
)
Where someArrayOfItems
would contain the array from either someArrayOfItems
or someArrayOfItems
. I’ve been trying to use JsonTransformingSerializer
to “rename” some-array-of-items
before the deserialization happens but am having trouble with the serializers for the SpecialType
not being used or something because when I use the transforming serializer then it doesn’t know how to handle “name”. I’m working to simplify the use case and will put an example of what I’ve tried here shortly.Jesse Hill
08/17/2021, 7:31 PMJesse Hill
08/17/2021, 7:44 PMobject TempTransformingSerializer : JsonTransformingSerializer<Temp>(Temp.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
val someArrayOfItemsWithDashes = element.jsonObject["some-array-of-items"]
return when {
someArrayOfItemsWithDashes != null -> {
buildJsonObject {
element.jsonObject.entries.forEach { (key, value) ->
when (key) {
"some-array-of-items" -> putJsonArray("someArrayOfItems") {
value.jsonArray.forEach { add(it) }
}
else -> put(key, value)
}
}
}
}
else -> super.transformDeserialize(element)
}
}
}
The input JSON was:
{
"data": [
{
"someValue": "value1",
"temp": {
"id": "thing1",
"someArrayOfItems": [
"one",
"two"
],
"other": [
{
"name_thing": "first thing"
}
]
}
},
{
"someValue": "value2",
"temp": {
"id": "thing2",
"some-array-of-items": [
"four",
"five"
],
"other": [
{
"name_thing": "second thing"
}
]
}
}
]
}
The classes I defined were:
@Serializable
data class TopLevel(
val data: List<SecondLevel>
)
@Serializable
data class SecondLevel(
val someValue: String,
@Serializable(with = TempTransformingSerializer::class)
val temp: Temp
)
@Serializable
data class Temp(
val id: String,
val someArrayOfItems: List<String>,
val other: List<Other>
)
@Serializable
data class Other(
@SerialName("name_thing")
val name: String
)
Dominaezzz
08/17/2021, 8:48 PMJsonNames
that allows you to provide alternative names for fields.Jesse Hill
08/17/2021, 8:50 PM