【问题标题】:Parsing JSON from HTTPResponse从 HTTPResponse 解析 JSON
【发布时间】:2012-10-03 22:10:39
【问题描述】:

我的 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

谁能建议我在我的代码中做错了什么?我该如何改进它?

【问题讨论】:

  • 我认为错误信息非常准确。您发布的 JSON 没有数组,只有普通对象。 JSON 语法位于 json.org

标签: java json httpresponse arrays


【解决方案1】:

我没有使用过那个特定的 API,但从对象名为 JSONArray(关键字:数组)这一事实来看,我猜它需要一个数组。使用 JSON,数组必须以 [ 开头并以 ] 结尾:

[1, 2, 3, 4]

它可以包含对象:

[{}, {}, {}]

注意对象如何以{ 开头并以} 结尾,这与数组不同:

{
    "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());

(再次,一个或另一个;不是两者。)

【讨论】:

  • @TechGeeky - 出于好奇,您使用了两种解决方案中的哪一种?
  • 这真的取决于你需要什么。根据您在问题中所说的,没有一种解决方案比另一种更好......但是如果还有其他因素 - 例如,如果您正在使用第 3 方 JSON 并且无法更改 JSON 数据 - 那么可能会有一个正确的选择和一个错误的选择。
【解决方案2】:

您的源 JSON 只是一个对象。而不是加载到数组中,直接加载到JSONObject 就足够了。

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

此对象将有一个名为 ipinfo 的属性。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 2019-02-21
    • 2011-06-25
    • 2012-07-05
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多