0

I am new to Kotlin and I want to make a simple JSON Object, I made the same code in Swift and had no problems. But now in the JSON object that I have a list of Doubles, after printing the JSON I see that the List is surrounded by " as it is a string value. How can I get rid of those "s?

Desired:

{
    "title": "need help moving",
    "description": "moving stuff from apartment",
    "points": 10,
    "loc" : { "coordinates" : [0,0], "type" : "Point" }
}

I have made the below code for it:

My Code So Far:

val loc = listOf(22.4577654, 22.4577654)
val locationObject = JSONObject()
locationObject.put("coordinates", loc)
locationObject.put("coor", loc as Any)
locationObject.put("type" ,"Point")
val params = JSONObject()

params.put("title", "$taskTitle")
params.put("description", "$taskDescription")
params.put("points", pointsEditText.text)
params.put("loc", locationObject)

But now my JSON looks like this:

Current Output:

{  
   "title":"This is Android Task",
   "description":"This is Android Task I made via the Android App :D",
   "points":"5",
   "loc":{  
      "coordinates":"[22.4577654, 22.4577654]",
      "coor":"[22.4577654, 22.4577654]",
      "type":"Point"
   }
}

Would be better if you suggest solutions without needing to install different libraries :)

Thanks

Mujtaba
  • 19
  • 1
  • 6
  • https://stackoverflow.com/questions/18563267/android-jsonobject-add-array-to-the-put-method – Tim Aug 02 '18 at 10:32

1 Answers1

0

You haven't added the list as a JsonArray but an object to your json. Instead you need to use the given JSONArray.

val array = JSONArray()
array.put(22.4577654)
array.put(22.4577654)

val locationObject = JSONObject()
locationObject.put("coordinates", array)
locationObject.put("coor", loc as Any)
locationObject.put("type" ,"Point")
val params = JSONObject()

params.put("title", "$taskTitle")
params.put("description", "$taskDescription")
params.put("points", pointsEditText.text)
params.put("loc", locationObject)
Mordag
  • 487
  • 7
  • 20