Home > Software engineering >  Trying unparse json string, but getting Expected start of the object '{', but had 'EO
Trying unparse json string, but getting Expected start of the object '{', but had 'EO

Time:11-25

I am trying to parse a json file into a list using kotlin serializable. Here are my data classes.

    @Serializable
data class Book(
    val epub : String,
    val fb2 : String,
    val mobi : String,
    val djvu : String,
    val title : String,
    val author : String,
    val anotation: String,
    val cover_uri : String,
)

@Serializable
data class Books(
    @Serializable (with = BookListSerializer::class)
    val books : List<Book>
)

object  BookListSerializer  :  JsonTransformingSerializer < List < Book >> ( ListSerializer ( Book.serializer ()))

Here I am trying to parse a string

val books = Json.decodeFromString<Books>(stringJson)

Here my Json String

[
  {
    "anotation": "Этот город",
    "author": "Чарльз Плэтт",
    "cover_uri": "null",
    "djvu": "null",
    "epub": "/b/301494/epub",
    "fb2": "/b/301494/fb2",
    "mobi": "/b/301494/mobi",
    "title": "New York Times (Пульс Нью-Йорка) (fb2)"
  },
  {
    "anotation": "Способна л",
    "author": "Триш Уайли",
    "cover_uri": "/i/45/390445/cover.jpg",
    "djvu": "null",
    "epub": "/b/390445/epub",
    "fb2": "/b/390445/fb2",
    "mobi": "/b/390445/mobi",
    "title": "Лучший мужчина Нью-Йорка (fb2)"
  }
]

And i always getting this error

kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead
    JSON input: .....2","mobi":"/b/49442/mobi","title":"I love New York (fb2)"}]

I would be very glad and grateful for any help

CodePudding user response:

tl;dr

Exchange this

val books = Json.decodeFromString<Books>(stringJson)

with this

val books = Json.decodeFromString<List<Book>>(stringJson)

You're trying to deserialize an JSON array [ ... ] but declare an object of type Books as target when calling decodeFromString, thus something like { books: [ ... ] }.

You either have to wrap your JSON array in the property books of an JSON object or change the expected type during deserialization to List<Book>.

Thus, besides the above solution, you could also do the following:

val wrappedStringJson = """
    {
      "books": $stringJson
    }
""".trimIndent()
val books = Json.decodeFromString<Books>(wrappedStringJson)
  • Related