6

I'm making a request to a request to an API and the response is a JSON object, this json object contains a string that is another json object. I'm trying to use kotlinx.serialization to handle the deserialization of this object.

I could override the deserialize functionality myself but that kind of defeats the point of using this library

I hoped something like this would have worked.

@Serializable
data class Foo(val data: Data)

@Serializable
data class Data(val foo: String)

For something like the following Object

{
  "data":"{\"foo\":\"bar\"}"
}

I expect to get an Object Foo with property data = Object Data with property foo = "bar"

However I get the following error

java.lang.IllegalStateException: Expected class kotlinx.serialization.json.JsonArray (Kotlin reflection is not available) but found class kotlinx.serialization.json.JsonLiteral (Kotlin reflection is not available)
Spiderbiggen
  • 61
  • 2
  • 3

1 Answers1

0

You did not specify how you are doing the deserialization. To get what you expect there you would have to specify the correct serializer.

val expectedFoo = Json.parse(Foo.serializer(), """{"data":{"foo":"bar"}}""")

Note In my answer I'm assuming you meant to use a slightly different example string.

In your example json string, the data key corresponds to a String value, not to an object. Please see the difference between the following:

{
  "data":"{\"foo\":\"bar\"}"
}
{
  "data": { "foo": "bar" }
}

So, in any situation, to parse that original example you would need to use some intermediate representation and parse the string representation in between.

@Serializable
data class Intermediate(val data: String)
//...
val intermediateFoo = Json.parse(Intermediate.serializer(), """{"data":"{\"foo\":\"bar\"}"}""")
val expectedFoo = Foo(data = Json.parse(Data.serializer(), intermediateFoo.data))
Mircea Nistor
  • 3,145
  • 1
  • 26
  • 32