Error "[ ] cannot be converted to JSON" when trying to create Jsonobject from String

Asked

Viewed 116 times

0

I am using the Kotlin language together with the GSON library to perform JSON object creation/parse.

I have the following string that caches a JSON object returned from a server

val jsonString = "{"age":22,"height":1.8,"profession":"Student","at_room":false,"gender":"male","pictures":[ ]}"

When I try to convert this string to a JSON Object by doing

val jsonData = JsonParser().parse(jsonString).asJsonObject

i get the following error: [] cannot be converted to JSON

I think the error is due to the fact that pictures be a Jsonarray and not a primitive type, but anyway I would like to know how to convert this string to a JSON Object correctly.

1 answer

0


I found the error, and unfortunately, it had nothing to do with transforming String into a JSON Object, but in converting the properties of the User class to a JSON String

My job was the following

override fun userToJson(user: User): String {

    return jsonObject(

            AGE_FIELD to user.age,
            HEIGHT_FIELD to user.height,
            EDUCATION_FIELD to user.education,
            WORK_FIELD to user.work,
            ABOUT_FIELD to user.about,
            GENDER_FIELD to user.gender,

            /* O erro era lançado nesta última linha */
            PICTURES_FIELD to jsonArray(user.albumPics)

    ).toString()
}

Analyzing the function jsonArray() vi that it takes as a parameter a set of values ( e.g. jsonArray("a","b","c") ), however, I was passing a user.albumPics, which is an object of the type MutableList<String>.

So what I should do is convert user.albumPics for a String representation user.albumPics.toString(), thus, the function call was jsonArray("[]") , what is valid.

So the final solution was to make a small change to the line

PICTURES_FIELD to jsonArray(user.albumPics)

replacing by

PICTURES_FIELD to jsonArray(user.albumPics.toString())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.