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

标签 java android json kotlin

编辑找到的解决方案:

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

问题:

我正在使用 JSONObject("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"
    }
  ]
}

它在我的 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 字符串吗?

最佳答案

由于您使用 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

关于java - 在 kotlin 中将 String 转换为 JsonObject 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285891/

相关文章:

java - 无法在 ant javascript 中导入类

java - 我可以在编译时链接 .jar,但不能在运行时链接

Android - 如何在 ListView 的背景上显示一条垂直线(并根据行高)?

android - android中的Base64图像转换导致图像损坏

javascript - 如何为 Heroku 创建和呈现 app.json 文件

java - ServerSocket.accept() 抛出 SocketTimeoutException 并显示 null 消息

java - hibernate 在 session.save(object) 上抛出 ClassCastException

android - 没有 FragmentActivity 的 DialogFragment

javascript - 启用/禁用带有虚拟文本区域的 Android 虚拟键盘

json - Postgres - 选择大型 jsonb 列的性能