从HTTPResponse解析JSON

ars*_*nal 3 java arrays json httpresponse

我的JSON看起来像这样 -

{"ipinfo": {
    "ip_address":"4.2.2.2",
     "ip_type":"Mapped",

                "Location":{

                            "continent":"north america",

                            "latitude":33.499,

                            "longitude":-117.662,

                        "CountryData":{

                                "country":"united states",

                                "country_code":"us"},

                        "region":"southwest",

                        "StateData":{

                                "state":"california",

                                "state_code":"ca"},

                        "CityData":{

                                "city":"san juan capistrano",

                                "postal_code":"92675",

                                "time_zone":-8}}

    }}
Run Code Online (Sandbox Code Playgroud)

这是我的下面代码,它试图访问JSONArray中的项目成员

    try {
        String url = service + version + method + ipAddress + format;
        StringBuilder builder = new StringBuilder();
        httpclient = new DefaultHttpClient();
        httpget = new HttpGet(url);
        httpget.getRequestLine();
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            for (String line = null; (line = bufferedReader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            //Exception getting thrown in below line
            JSONArray jsonArray = new JSONArray(builder.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
            }
        }

    } catch (Exception e) {
        getLogger().log(LogLevel.ERROR, e.getMessage());
    } finally {
        bufferedReader.close();
        httpclient.getConnectionManager().shutdown();
    }
Run Code Online (Sandbox Code Playgroud)

我总是在这条线上被抛出异常 -

JSONArray jsonArray = new JSONArray(builder.toString());
Run Code Online (Sandbox Code Playgroud)

以下是抛出的异常

org.json.JSONException: A JSONArray text must start with '[' at character 1
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议我在我的代码中做错了什么?我该如何改进呢?

Ric*_*uen 5

我没有使用过那个特定的API,但是从对象命名的事实判断JSONArray(关键字:数组)我猜它会期望一个数组.使用JSON,数组必须以a开头[并以]:

[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

它可以包含对象:

[{}, {}, {}]
Run Code Online (Sandbox Code Playgroud)

注意对象的开头{和结尾方式},与数组不同:

{
    "name": "My Object!"
}
Run Code Online (Sandbox Code Playgroud)

由于你的JSON数据看起来更像是{object}一个[array]或许你应该尝试使用JSONObject.

实际上,您有两个选择:可以将JSON数据更改为数组,也可以更改要使用的Java代码JSONObject.(一个或另一个;不是两个.)

更改JSON数据

就像[在开头和]结尾添加一样简单:

[
    {
        "ipinfo": {
            "ip_address": "4.2.2.2",
            "ip_type": "Mapped",
            "Location": {
                "continent": "north america",
                "latitude": 33.499,
                "longitude": -117.662,
                "CountryData": {
                    "country": "united states",
                    "country_code": "us"
                },
                "region": "southwest",
                "StateData": {
                    "state": "california",
                    "state_code": "ca"
                },
                "CityData": {
                    "city": "san juan capistrano",
                    "postal_code": "92675",
                    "time_zone": -8
                }
            }
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

改变Java

最终的Java看起来有点像:

// OLD CODE
//JSONArray jsonArray = new JSONArray(builder.toString());
//for (int i = 0; i < jsonArray.length(); i++) {
//    JSONObject jsonObject = jsonArray.getJSONObject(i);
//}
// END OLD CODE
JSONObject jsonObject = new JSONObject(builder.toString());
Run Code Online (Sandbox Code Playgroud)

(同样,一个或另一个;不是两个.)