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?
}
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?
}
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.
I think you can do something like this:
I might be wrong though...
Source: GitHub issue