一尘不染

Java将字符串转换为JSON数组

java

我从网络服务获取以下JSON字符串,并尝试将其转换为 JSONarray

{
    "locations": [
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        }
    ]
}

我String在线上对此进行了验证,这似乎是正确的。现在我在android开发中使用以下代码来利用

JSONArray jsonArray = new JSONArray(readlocationFeed);

这会引发异常和类型不匹配的异常。


阅读 2864

收藏
2020-03-07

共1个答案

一尘不染

在这里,你将获得JSONObject,因此请更改以下行:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

具有以下内容:

JSONObject jsnobject = new JSONObject(readlocationFeed);

之后

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}
2020-03-07