我想从来自此 JSON 文件的字符串中获取 json 对象:
{
"categories": {
"category": [
{
"label": "Collaboration",
"thumbnail": "http://mywebite.com/dfsv",
"description": "...",
"contents": {
"@attributes": {
"count": "79"
}
},
"@attributes": {
"id": "ZSQYN2"
}
},
{
"label": "Communication",
"thumbnail": "http://mywebite.com/dfsv",
"description": "...",
"contents": {
"@attributes": {
"count": "43"
}
},
"@attributes": {
"id": "uGQ9MC"
}
}
],
"@attributes": {
"page": "12",
"limit": "0",
"count": "111",
"lang": "en"
}
}
}
我正在使用此代码:
JSONObject obj = new JSONObject(myString);
我收到此错误消息:
Value ... of type org.json.JSONArray cannot be converted to JSONObject
如果我这样做:
JSONArray obj = new JSONArray(myString);
我收到此错误消息:
Value ... of type org.json.JSONObject cannot be converted to JSONArray
...
你有什么想法吗?
最佳答案
JSONArray
和 JSONObject
是两个不同的东西,并且不应该彼此类型兼容,因此这些错误是有道理的。这是一个 JSONArray:
["foo", "bar", "baz"]
这是一个 JSONObject:
{ "foo": "bar", "baz": "quux"}
您可能正在寻找 JSONElement
,它位于 Google's GSON 等 API 中。是数组和对象之间的公共(public)父类(super class)。
Android下JSON API它们也不类型兼容。
关于java - java中JSONArray无法转换为JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23134577/