java - java中JSONArray无法转换为JSONObject

标签 java android json

我想从来自此 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

...

你有什么想法吗?

最佳答案

JSONArrayJSONObject 是两个不同的东西,并且不应该彼此类型兼容,因此这些错误是有道理的。这是一个 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/

相关文章:

ruby-on-rails - Rails JSON 多重嵌套关联

java - 使用 java nio 套接字时,“已建立的连接被主机中的软件中止”

android - APK 文件在直接构建时安装,但在使用分发过程创建 .apk 文件时不安装 (Titanium Studio)

json - 将具有 JSON 数组的 JSON 对象解码为结构

android - 具有单个字符串值的失败的 BINDER 事务,RecycleView/Firebase

android - 带有@Inject 注释的 ProGuard 和 RoboGuice 的问题

json - jq 在 bash 中区分 json

java - Mule - Web 应用程序和 Mule ESB 之间的通信

java - Java `this` 在继承情况下实际指的是什么?

java - Android JSON 解析与转换