"Can not be converted to JSON" error when trying to create JSONObject from String

0

I'm using the Kotlin language together with the GSON library to do parse creation / parsing of JSON objestos.

I have the following string that stores 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, 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 is a JSONArray and not a primitive type, but anyway I'd like to know how to convert this string to a JSON Object correctly.

    
asked by anonymous 05.05.2016 / 21:14

1 answer

0

I found the error, and unfortunately, it did not have to do with the transformation of the String into a JSON Object, but rather the conversion of the properties of the User class to a JSON String

My job that did this conversion was as follows

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()
}

I want to be able to do this, but I'm not sure how to do this, but I'm not sure how to do this. >

So, what I should do was convert jsonArray() to a String representation by doing jsonArray("a","b","c") , so the function call was user.albumPics , which is valid.

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

PICTURES_FIELD to jsonArray(user.albumPics)

replacing with

PICTURES_FIELD to jsonArray(user.albumPics.toString())
    
07.05.2016 / 22:31