简体   繁体   中英

Parsing JSON from HTTPResponse

My JSON looks like this-

{"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}}

    }}

This is my below code which tries to access members of items in a 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();
    }

I am always getting exception thrown at this line-

JSONArray jsonArray = new JSONArray(builder.toString());

Below is the exception getting thrown

org.json.JSONException: A JSONArray text must start with '[' at character 1

Can anyone suggest me what wrong I am doing in my code? And how can I improve it?

I haven't used that particular API, but judging by the fact that the object is named JSONArray (keyword: array) I'm going to guess it expects an array. Using JSON, an array has to begin with a [ and end with ] :

[1, 2, 3, 4]

It can contain objects:

[{}, {}, {}]

Note how the objects begin with { and end with } , unlike the arrays:

{
    "name": "My Object!"
}

Since your JSON data looks more like an {object} than an [array] maybe you should try using JSONObject instead.

Really though you have two options: you can change the JSON data to be an array, or you can change the Java code to use JSONObject . (One or the other; NOT both.)

Changing the JSON data

As simple as adding a [ at the beginning and ] at the end:

[
    {
        "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
                }
            }
        }
    }
]

Changing the Java

The final Java would look a little something like:

// 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());

(Again, one or the other; NOT both.)

Your source JSON is just a single object. Instead of loading into an array, loading straight into a JSONObject should suffice.

JSONObject jsonObject = new JSONObject(builder.toString());

This object will have a single property named ipinfo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM