gpt4 book ai didi

java - 从 HTTPResponse 解析 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:30:12 25 4
gpt4 key购买 nike

我的 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(关键字:array)的事实来判断,我猜它需要一个数组。使用 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());

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

关于java - 从 HTTPResponse 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12870163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com