Michael Peters
Michael Peters

Reputation: 40

Null or Empty Object parsing in Kotlinx.serialization

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

Answers (2)

Steven Jeuris
Steven Jeuris

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

mikayelgrigoryan
mikayelgrigoryan

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

Related Questions