Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying unparse json string, but getting Expected start of the object '{', but had 'EOF' instead

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading