java 从 HTTPResponse 解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12870163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON from HTTPResponse
提问by arsenal
My JSON looks like this-
我的 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}}
}}
This is my below code which tries to access members of items in a JSONArray
这是我下面的代码,它尝试访问 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?
谁能建议我在我的代码中做错了什么?我该如何改进它?
回答by Richard JP Le Guen
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 ]
:
我没有使用过那个特定的 API,但是根据对象被命名为JSONArray
(keyword: array)的事实判断,我猜它需要一个数组。使用 JSON,数组必须以 a 开头并以[
结尾]
:
[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.
由于您的 JSON 数据看起来更像是 an 而{object}
不是 an[array]
也许您应该尝试使用它JSONObject
。
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.)
实际上,尽管您有两个选择:您可以将 JSON 数据更改为数组,或者您可以将 Java 代码更改为使用JSONObject
. (一个或另一个;不是两个。)
Changing the JSON data
更改 JSON 数据
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
改变 Java
The final Java would look a little something like:
最终的 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());
(Again, one or the other; NOT both.)
(同样,一个或另一个;不是两个。)
回答by meklarian
Your source JSON is just a single object. Instead of loading into an array, loading straight into a JSONObject
should suffice.
您的源 JSON 只是一个对象。而不是加载到数组中,直接加载到 aJSONObject
应该就足够了。
JSONObject jsonObject = new JSONObject(builder.toString());
This object will have a single property named ipinfo
.
该对象将有一个名为 的属性ipinfo
。