0

I'm using the Koltin language with GSON library to create/parse JSON. I have the following string that represents a JSON object

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:

[] can not be converted to JSON

I guess that this error is due to the fact that pictures is a JSONArray and not a primitive type. Anyway, I would like to know how to convert this string to a JSON Object correctly.

sargue
  • 5,695
  • 3
  • 28
  • 43
regmoraes
  • 5,329
  • 3
  • 24
  • 33

1 Answers1

1

Your code is fine, there is something else that is failing.

I've tried this and it works.

package proves

import com.google.gson.JsonParser

fun main(args: Array<String>) {
    val jsonString = "{ \"age\": 22, \"height\" : 1.8, \"profession\":\"Student\", \"at_room\": false, \"gender\": \"male\",\"pictures\": []}"
    val jsonData = JsonParser().parse(jsonString).asJsonObject
    print(jsonData)
}

Output:

{"age":22,"height":1.8,"profession":"Student","at_room":false,"gender":"male","pictures":[]}
sargue
  • 5,695
  • 3
  • 28
  • 43