Null or Empty Object parsing in Kotlinx.serialization

2.1k Views Asked by At

How to parse both types of responses:

{
"x" : "some_string"
}

and

{
"x" : { } 
}

Into a data class that looks like:

@Serializable
data class SomeClass {
  
   @SerialName("x")
   val x : String?
}
2

There are 2 best solutions below

3
On

I think you can do something like this:

@Serializable
data class Foo {
   @SerialName("bar")
   val bar: String? = null
}

I might be wrong though...

Source: GitHub issue

0
On

This will only work by writing a custom serializer which you apply to the x field.

String is a primitive (JsonPrimitive). {} is an object (JsonObject). You seem to be encoding null as an empty JsonObject here, and when the value is set, you encode it as a JsonPrimitive.

If this is a strict requirement, you need to write a custom serializer that translates an empty object to null, which should be fairly trivial. You probably also want the serialization to fail in case this object contains any keys.

However, the idiomatic way would be to simply encode this as null, in which case the default kotlinx.serialization serializer would work; it takes care of nullable types.