Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,JSONArray无法转换为JSONObject_Java_Android_Json - Fatal编程技术网

在java中,JSONArray无法转换为JSONObject

在java中,JSONArray无法转换为JSONObject,java,android,json,Java,Android,Json,我想从这个json文件的字符串中获取一个json对象: { "categories": { "category": [ { "label": "Collaboration", "thumbnail": "http://mywebite.com/dfsv", "description": "...", "contents": { "@attribu

我想从这个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);
我收到了这个错误信息:

价值。。。无法将org.json.JSONArray类型的转换为JSONObject

如果我这样做了:

JSONArray obj = new JSONArray(myString);
我收到了以下错误消息:

价值。。。无法将org.json.JSONObject类型的转换为JSONArray


你知道吗?

JSONArray
JSONObject
是两个不同的东西,它们之间不应该是类型兼容的,所以这些错误是有意义的。这是一个JSONArray:

[“foo”、“bar”、“baz”]

这是一个JSONObject:

{“foo”:“bar”,“baz”:“quox”}

您可能正在寻找
JSONElement
,它在类似API的API中是数组和对象之间的公共超类


在安卓系统下,它们的类型也不兼容。

我终于找到了解决方案

我换了

JSONObject obj = new JSONObject(myString);
作者:

找到答案


希望它能帮助别人

你确定myString在两种情况下都是相同的吗?是的,它是相同的字符串
JSONObject obj = new JSONObject(myString.substring(myString.indexOf("{"), myString.lastIndexOf("}") + 1));