我是Kotlin
的新手,我想创建一个简单的JSON
对象,我在Swift
中做了相同的代码,没有任何问题。
但是现在在JSON
对象中,我有list
个Double
,在打印JSON之后,我看到列表被"
包围了,因为它是一个字符串值。我如何摆脱那些"
?
所需:
{
"title": "need help moving",
"description": "moving stuff from apartment",
"points": 10,
"loc" : { "coordinates" : [0,0], "type" : "Point" }
}
我为此编写了以下代码:
到目前为止我的代码:
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)
但是现在我的JSON看起来像这样:
当前输出:
{
"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"
}
}
如果您建议解决方案而不需要安装其他库,那就更好了:)
谢谢
答案 0 :(得分:0)
您尚未将列表作为JsonArray添加,而是将对象添加到json。相反,您需要使用给定的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)
答案 1 :(得分:0)
我认为您应该坚持使用这种格式。
{
"title": "need help moving",
"description": "moving stuff from apartment",
"points": 5,
"loc": {
"latitude": 22.4577654,
"longitude": 22.4577654,
"type": "Point"
}
}
您的代码:
val loc = doubleArrayOf(22.4577654, 22.4577654)
val locationObject = JSONObject()
locationObject.put("latitude", loc[0])
locationObject.put("longitude", loc[1])
locationObject.put("type" ,"Point")
val params = JSONObject()
params.put("title", "$taskTitle");
params.put("description", "$taskDescription")
params.put("points", pointsEditText.text.toDouble())
params.put("loc", locationObject)