3

当我尝试将 JSON 字符串转换为 JSONObject 时出现以下错误。

java.lang.String 类型位置的值48.466667|9.883333无法转换为 JSONObject

字符串是有效的 JSON,我用http://jsonlint.com/对其进行了测试

示例:{"name":"An der Decke","location":" 48.412583|10.0385 ","type":"Virtual","size":null,"status":"Available","difficulty":1 “评级”:空,“地形”:1}

产生异常的代码如下所示:

jsonObject = new JSONObject(result);
jsonArray = new JSONArray();
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        JSONObject value = (JSONObject) jsonObject.get(key);   <---- Exception
        jsonArray.put(value);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

是管子| 符号不是Java JSON中的有效字符?

编辑:

问题是,如果 JSON 字符串不包含"location":"48.412583|10.0385"部分,它可以正常工作......

4

3 回答 3

2

您似乎误解了org.json图书馆的工作方式。

JSON 主页上所述,JSON 值可以是字符串、数字、对象、数组、true/false 或 null。该库将这些值类型映射到StringNumber子类JSONArrayJSONObjectBooleannull

并非该库中的所有内容都是JSONObject. 实际上,aJSONObject专门用于表示名称/值对对象。JSONObject.get()可能会返回任何上述值类型,这就是为什么它需要回退到最大公分母类型:(Object不是 JSONObject)。因此,将所有内容都转换为 a 是JSONObject行不通的。

您有责任使用您对传入数据结构的了解来确保转换为正确的类型。在您的情况下,这似乎是一个问题:您的 JSON 字符串包含字符串(for name、和)、整数(for和)和空值(for )。你到底想用这些做什么?locationtypestatusdifficultyterrainsize

于 2013-08-22T20:22:40.130 回答
0

如果您的目标只是获取JSONArray所有 JSON 字符串值中的一个,那么有一种更简单的方法可以做到这一点。

JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.toJSONArray(jsonObject.names());

System.out.println(jsonArray); // prints:
// [1,"Available","48.412583|10.0385","An der Decke",1,null,"Virtual",null]

除此之外,您错误地认为封装在 JSON 中的每个值都是 JSON 对象本身。事实上,在你的情况下,它们都不是。JSON 中所有值的正确类型是

// String
System.out.println(jsonObject.getString("name")); // An der Decke
System.out.println(jsonObject.getString("location")); // 48.412583|10.0385
System.out.println(jsonObject.getString("type")); // Virtual
System.out.println(jsonObject.getString("status")); // Available

// Null
System.out.println(jsonObject.isNull("size")); // true
System.out.println(jsonObject.isNull("rating")); // true

// Integer
System.out.println(jsonObject.getInt("terrain")); // 1
System.out.println(jsonObject.getInt("difficulty")); // 1

另一方面,如果您name是一个由名字、中间名和姓氏组成的嵌入式 JSON 对象,则您的 JSON 字符串(为简洁起见忽略其余键)看起来像

{"name": {"fname" : "An", "mname" : "der", "lname" : "Decke"}}

现在,我们可以getJSONObject()使用了,因为我们确实有一个嵌入的 JSON 对象。

JSONObject jsonObj = new JSONObject("{\"name\":
                     {\"fname\" : \"An\", \"mname\" : \"der\", \"lname\" : \"Decke\"}}");

// get embedded "name" JSONObject
JSONObject name = jsonObj.getJSONObject("name");

System.out.println(name.getString("fname") + " "
                 + name.getString("mname") + " "
                 + name.getString("lname")); // An der Decke
于 2013-08-22T20:25:41.780 回答
0

get()方法JSONObject返回类型的结果Object。在这种情况下,它似乎是一个String. 就好像你在做

JSONObject value = (JSONObject) new String("asdasdsa");

这显然没有意义,因为它们是不兼容的类型。

相反,检索该值,从中创建一个JSONObject并将其添加到JSONArray.

于 2013-08-22T20:05:30.593 回答