编辑:
在我的代码中发现错误。我在单元测试上运行此程序,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字符串吗?
答案 0 :(得分:0)
substring
的JSON字符串。将其放在JSONObject
内,它将正常工作。getJSONObject
或getJSONArray
方法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