【发布时间】:2019-07-31 07:58:34
【问题描述】:
编辑找到的解决方案:
在我的代码中发现错误。我在单元测试中运行它,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"
}
]
}
它在我的 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())
this 的所有输出均为空。有什么方法可以知道发生了什么错误,以便我可以调整我的 json 字符串?
【问题讨论】:
-
也许创建一个pojo模型并使用Gson库更好?还是你没有这样的机会?
-
试试Retroft,更快更简单。
-
@SergeiMikhailovskii 这只是从本地 json 文本文件读取的简单单元测试。是的,这是可能的,但我想知道为什么这段代码不起作用。