Search code examples
kotlinkotlinx.serialization

Deserialize JsonArray with kotlinx serialization


I have the following Json object:

{
  "List":[
      "string1",
      "string2",
      "string3",
      "..."
   ]
}

This deserializes into a JsonArray containing JsonLiterals. When deserializing this and trying to iterate over it I get an error:

java.lang.ClassCastException: kotlinx.serialization.json.JsonLiteral cannot be cast to java.lang.String

What would be the standard way to achieve something like that?


Solution

  • First, make sure that you are using the latest version of kotlinx.serialization.
    A comment in the implementation of JsonLiteral states that

    JsonLiteral is deprecated for public use and no longer available. Please use JsonPrimitive instead

    JsonPrimitive has the isString method to check if it is a string and you can then access it using its content method.