簡體   English   中英

從HTTPResponse解析JSON

[英]Parsing JSON from 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}}

    }}

這是我的下面代碼,它試圖訪問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();
    }

我總是在這條線上被拋出異常 -

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

以下是拋出的異常

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

任何人都可以建議我在我的代碼中做錯了什么? 我該如何改進呢?

我沒有使用過那個特定的API,但是從對象命名為JSONArray (關鍵字:數組)的事實來看,我猜它會期望一個數組。 使用JSON,數組必須以[和end with ]開頭:

[1, 2, 3, 4]

它可以包含對象:

[{}, {}, {}]

注意對象如何以{和end with }開頭,與數組不同:

{
    "name": "My Object!"
}

由於您的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
                }
            }
        }
    }
]

改變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());

(同樣,一個或另一個;不是兩個。)

您的源JSON只是一個對象。 而不是加載到數組中,直接加載到JSONObject就足夠了。

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

該對象將具有名為ipinfo的單個屬性。

暫無
暫無

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

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