java.lang.String类型的值无法转换为JSONArray

时间:2015-11-19 09:37:36

标签: java android json string

我有一个非常大的常量JSONArray来自Webservice,为了减少数据传输,我想把它放在Android中。我记录了所有JSONArray(来自webservice),将其放在一个字符串中并转换为JSONArray。这是我写的代码:

String additionString =  ""Additions":[{"AdditionID":0,"Type":-1,"Long":" ","Short":" "},{"AdditionID":8,"Type":6,"Long":"English,"Short":"Eng"},{"AdditionID":11,"Type":2,"Long":"French","Short":"Fr."},{"AdditionID":12,"Type":2,"Long":"German","Short":"Ger."}]";

JSONArray AdditionArray = new JSONArray(additionString);

我为此收到了这个错误:

  

无法将java.lang.String类型的值添加转换为   JSONArray

顺便说一下,Android Studio中的字符串如下所示:

 String additionString =  "\"Additions\":[{\"AdditionID\":0,\"Type\":-1,\"Long\":\" \",\"Short\":\" \"},{\"AdditionID\":8,\"Type\":6,\"Long\":"English,\"Short\":\"Eng\"},{\"AdditionID\":11,\"Type\":2,\"Long\":\"French\",\"Short\":\"Fr.\"},{"AdditionID":12,"Type":2,"Long":"German","Short":"Ger."}]";

如何将该String转换为JSONArray?感谢。

3 个答案:

答案 0 :(得分:2)

 ""Additions":[{"AdditionID":0,"Type":-1,"Long":" ","Short":" "},{"AdditionID":8,"Type":6,"Long":"English,"Short":"Eng"},{"AdditionID":11,"Type":2,"Long":"French","Short":"Fr."},{"AdditionID":12,"Type":2,"Long":"German","Short":"Ger."}]"

既不是有效JSONObject也不是有效JSONArray。 JSONObject以{}

开头和结尾
{
    "Additions": [
        {
            "AdditionID": 0,
            "Type": -1,
            "Long": " ",
            "Short": " "
        },
        {
            "AdditionID": 8,
            "Type": 6,
            "Long": "English",
            "Short": "Eng"
        }
    ]
}

有效的JSONArray将是

[
    {
        "AdditionID": 0,
        "Type": -1,
        "Long": " ",
        "Short": " "
    },
    {
        "AdditionID": 8,
        "Type": 6,
        "Long": "English",
        "Short": "Eng"
    }
]

答案 1 :(得分:1)

JSONArray以[]开头,JSONObject以{}开头。

因此,如果您想在JSONArray中转换字符串而不是将字符串更改为

String additionString =  "[{'AdditionID':0,'Type':-1,'Long':' ','Short':' '},
{'AdditionID':8,'Type':6,'Long':'English','Short':'Eng'},
{'AdditionID':11,'Type':2,'Long':'French','Short':'Fr.'},
{'AdditionID':12,'Type':2,'Long':'German','Short':'Ger.'}]";

答案 2 :(得分:1)

你要解析的json字符串有问题(" Long":"英语不以&#34结尾;)另外,字符串应该是jsonobject(在{}内)或者jsonArray。 因此,您可以按如下方式执行所需的操作:

String s="{\"Additions\":[{\"AdditionID\":0,\"Type\":-1,\"Long\":\" \",\"Short\":\" \"},{\"AdditionID\":8,\"Type\":6,\"Long\":\"English\",\"Short\":\"Eng\"},{\"AdditionID\":11,\"Type\":2,\"Long\":\"French\",\"Short\":\"Fr.\"},{\"AdditionID\":12,\"Type\":2,\"Long\":\"German\",\"Short\":\"Ger.\"}]}";


        JSONObject jsonObject=new JSONObject(s);
        JSONArray jsonArray=jsonObject.getJSONArray("Additions");

        System.out.print(jsonArray.getJSONObject(0).getString("Type"));