【问题标题】:Kotlin JSON Double List as value is stringKotlin JSON 双列表作为值是字符串
【发布时间】:2018-08-03 11:20:41
【问题描述】:

我是Kotlin 的新手,我想制作一个简单的JSON 对象,我在Swift 中制作了相同的代码并且没有问题。 但是现在在JSON 对象中,我有一个listDoubles,在打印JSON 之后,我看到列表被" 包围,因为它是一个字符串值。我怎样才能摆脱那些"s?

期望:

{
    "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"
   }
}

如果您在不需要安装不同库的情况下提出解决方案会更好:)

谢谢

【问题讨论】:

标签: android json kotlin


【解决方案1】:

您没有将列表作为 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多