簡體   English   中英

JSONArray無法在Java中轉換為JSONObject

[英]JSONArray cannot be converted to JSONObject in java

我想從來自此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

...

你有什么主意嗎 ?

JSONArrayJSONObject是兩個不同的事物,並且不應在類型上相互兼容,因此這些錯誤是有道理的。 這是一個JSONArray:

["foo", "bar", "baz"]

這是一個JSONObject:

{ "foo" : "bar", "baz" : "quux" }

您可能正在尋找JSONElement ,在像Google的GSON這樣的API中, JSONElement是數組和對象之間的通用超類。

在Android JSON API下,它們也不兼容類型。

我終於找到了解決方案!

我更換了

JSONObject obj = new JSONObject(myString);

創建人:

JSONObject obj = new JSONObject(myString.substring(myString.indexOf("{"), myString.lastIndexOf("}") + 1));

這里找到答案

希望能對某人有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM