所以我一般都是json解析的新手。在社区的帮助下,我能够让json返回。但是,对于我的生活无法弄清楚如何访问/获取某些值。我想要/访问" halfjpeg" "内容中的价值"部分。
[
{
"publicId": "1337",
"name": "mypainting",
"orientation": "vertical",
"provider": "user",
"providerFullName": "unknown",
"location": {
"coordinates": [
-71,
42
],
"userCityCode": "BOS",
"userCityName": "Boston",
"userStateCode": "MA",
"userStateName": "Massachusetts",
"userCountryCode": "US",
"userCountryName": "United States",
"userZipCode": "02108",
"latitude": 42
"longitude": -71
},
"status": {
"isLive": false,
"isCertified": false,
"hasVirusWarning": true
},
"content": {
"halfJpeg": "userhalfpaintlocation.com",
"fullJpeg": "userfullpaintlocation.com",
"hugeJpeg": "userhugepaintlocation.com"
},
"createdAt": xxxxxxxx,
"updatedAt": xxxxxxxx,
"policy": {
"isAdmin": false,
"isUser": true
}
}
]
我的获取JSON的代码如下:
URL url = null;
try {
url = new URL("getthepaintingurl.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
conn.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
try {
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
InputStream in = null;
try {
in = new BufferedInputStream(conn.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(out.toString());
try {
JSONObject jObject = new JSONObject(out.toString());
} catch (JSONException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
只是你知道一些语法,阅读上面的内容(它应该有助于澄清!)。
您期望的回答是JSONArray的形式。所以它看起来像这样:
//create json array from the buffer string, and get the inner json object
JSONObject response = new JSONArray(out.toString()).getJSONObject(0);
//get the json object at key "content"
JSONObject content = response.getJSONObject("content");
//access the value of "halfJpg"
String halfJpgSrc = content.getString("halfJpeg");
注释应该自己解释,但实际上你从请求的输出中创建了一个JSONArray,并访问包含所有信息的内部json对象(索引0)。然后,您只需导航到您发送的数据。在这种情况下,内部数据存储在键/值对中,因此如何访问JSON响应中的任何其他内容应该是非常自我解释的。
以下是关于这两个对象的更多文档(JSONArray / JSONObject)