Reputation: 40
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?
}
Upvotes: 0
Views: 3015
Reputation: 19130
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.
Upvotes: 1
Reputation: 563
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
Upvotes: 0