在 kotlin 中将 String 转换为 JsonObject 返回 null

Mar*_*lon 8 java android json kotlin

编辑找到的解决方案:

在我的代码中发现了错误。我在单元测试中运行它,Android 在单元测试中不使用 JSON 对象,因为它是 android 的一部分。这就是它返回 null 的原因。

问题:

我正在使用 JSONObject("string") 将我的 String 转换回 JsonObject

这是我的字符串的示例:

{
  "sessions": [
    {
      "locations": [
        {
          "lat": "14.2294625",
          "lng": "121.1509005",
          "time": 1560262643000,
          "speed": 0,
          "speedLimit": 0
        },
        {
          "lat": "14.2294576",
          "lng": "121.1509498",
          "time": 1560262713000,
          "speed": 0,
          "speedLimit": 0
        },
        {
          "lat": "14.2294576",
          "lng": "121.1509498",
          "time": 1560262714000,
          "speed": 0,
          "speedLimit": 0
        }
      ],
      "name": "1.5645220491E12"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

它在我的 JsonObjects 上返回 null:

content = "the string above"

var obj = JSONObject(content.substring(content.indexOf("{"), content.lastIndexOf("}") + 1))
System.out.println("obj1: " + obj.toString())

obj = JSONObject(content)
System.out.println("obj1: " + obj.toString())

var obj1 = JSONArray(content)
System.out.println("obj1: " + obj1.toString())

obj1 = JSONArray(content.substring(content.indexOf("{"), content.lastIndexOf("}") + 1))
System.out.println("obj2: " + obj1.toString())
Run Code Online (Sandbox Code Playgroud)

所有的输出都是空的。有什么方法可以知道发生了什么错误,以便我可以调整我的 json 字符串吗?

Mar*_*iev 2

  1. 不需要substring您的 JSON 字符串。把它放进去就JSONObject可以正常工作了。
  2. 如果您需要获取嵌套对象,请使用getJSONObjectgetJSONArray方法
  3. 在代码中显示您的content字符串(或者如何加载它)

您编辑的代码

val content = "the string above"

var obj = JSONObject(content)
Run Code Online (Sandbox Code Playgroud)

  • 已经这样做了,你可以在我的代码中看到我尝试了许多不同的方法将其转换为对象,所有方法都返回 null。 (3认同)