https://kotlinlang.org logo
#serialization
Title
# serialization
n

nkiesel

03/18/2023, 8:36 PM
Hi, I need to (only) deserialize some JSON I do not control:
Copy code
[ { "item": "first" }, { "item": { "name": "second", "value": 3 }, { "item": "last" } ]
and I thought I could use sealed classes for this. However, this does not work because the item value is sometime not an object but just a string. What is the best approach handling this? Note: I tried to simplify my real data, but that might lead to misleading answers. I reality, these "items" are nested values in some larger JSON:
Copy code
{
  "id": 3,
  "data": [
    {
      "data": {
        "id": 4,
        "item1": "i1",
        "item2": {
          "k": "k1",
          "v": 1
        }
      }
    },
    {
      "data": {
        "id": 4,
        "item1": {
          "k": "i2",
          "v": 3
        },
        "item2": {
          "k": "k4",
          "v": 1
        }
      }
    }
  ]
}
so really the issue it that items are sometimes strings and sometimes objects.
a

Adam S

03/18/2023, 9:43 PM
one simple solution is to decode to JsonElement and then write some Kotlin code to convert/filter/manipulate the resulting objects
n

nkiesel

03/18/2023, 10:07 PM
Yeah, that's an option. I also saw suggestions to use
Any
, but I was hoping for some type-safe and declarative approach.
a

Adam S

03/19/2023, 12:05 PM
you can use JsonContentPolymorphicSerializer, which is a slightly more structured way of using JsonObject :) https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#content-based-polymorphic-deserialization
4 Views