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

时间:2019-07-31 07:58:34

标签: java android json kotlin

编辑:

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

问题:

我想使用JSONObject(“ string”)将我的String转换回JsonObject

以下是我的String的示例:

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

它在我的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())

所有此输出为空。有什么办法知道会发生什么错误,以便我可以调整json字符串吗?

3 个答案:

答案 0 :(得分:0)

  1. 不需要substring的JSON字符串。将其放在JSONObject内,它将正常工作。
  2. 如果您需要使用嵌套对象,请使用getJSONObjectgetJSONArray方法
  3. 在代码中显示您的content字符串(或如何加载)

您编辑的代码

val content = "the string above"

var obj = JSONObject(content)

答案 1 :(得分:0)

我运行此功能来解析您的字符串,没关系。您的字符串是有效的。您能指定如何初始化val content

 fun parseJson() {
    var stringJson = "{\"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\"}  ]}"

    var obj = JSONObject(stringJson)
    System.out.println("obj1: $obj")
    var sessionArray: JSONArray = obj.optJSONArray("sessions")
    System.out.println("obj1: $sessionArray")
    var firstObject = sessionArray[0]
    System.out.println("obj1: $firstObject")
}

答案 2 :(得分:0)

由于使用Junit运行代码,因此代码在计算机上的SDK上运行。该SDK不能提供所有内容,有些只是一些框架类,提供方法和文档的签名,但不提供代码。所以你不能直接执行。

尝试在测试中添加库

testImplementation 'org.json:json:your_version'

在此处查看版本:

http://mvnrepository.com/artifact/org.json/json

这是基于此帖子的答案:JSONObject returns a non null value of "null" after instantiating with string