Hello, I wonder if there is a nice way to handle l...
# serialization
c
Hello, I wonder if there is a nice way to handle less than ideal API schemas (Home Assistant websocket api) 🧵
There is a response type of 'result' that has the following JSON structure:
Copy code
{
   "type":"result",
   "result": {} | []
}
The result field can contain a single instance of an item, or a list of that particular item. Is my only option a custom serializer?
👌 1
rargh, this API is so frustrating, there's absolutely no other indication in the JSON body that can let you know whether or not the
result
field will contain an array or an object and I can't see anyway to interrogate what the next symbol is going to be in the
KSerializer
implementation (via the decoder instance)
a
It seems like JsonTransformingSerializer is probably what you're looking for
Something like this maybe:
Copy code
@Serializable
data class Data(
    val type: String,
    
    @Serializable(with = OneOrManySerializer::class) 
    val result: List<Result>
)

class OneOrManySerializer<T>(serializer: KSerializer<T>) :
    JsonTransformingSerializer<List<T>>(ListSerializer(serializer)) {
        
    override fun transformDeserialize(element: JsonElement): JsonArray =
        if (element is JsonArray) element
        else JsonArray(listOf(element))
    
}
Which will transform the item to always be a list
c
I didn't think about adding that to the field! Amazing, I'll give it a go, that'll clean up tons if it works!