我正在使用Instagram REST API,需要从JSON响应中获取图像链接。
JSON类似于以下内容:
{
"meta":
{
"code": 200
},
"data":
{
"attribution": null,
"tags":
[
"tag"
],
"type": "image",
"location": null,
"comments":
{
"count": 7
},
"filter": "Normal",
"created_time": "1451066377",
"link": "https://www.instagram.com/p/at3rg7uj_9/",
"likes":
{
"count": 39
},
"images":
{
"low_resolution":
{
"url": "https://url.jpg",
"width": 320,
"height": 320
},
"thumbnail":
{
"url": "https://url.jpg",
"width": 150,
"height": 150
},
"standard_resolution":
{
"url": "https://url.jpg?ig_cache_key=key",
"width": 640,
"height": 640
}
},
"users_in_photo":
[
],
"caption":
{
"created_time": "1451066377",
"text": "caption",
"from":
{
"username": "f",
"profile_picture": "https://profilepic.jpg",
"id": "185333924",
"full_name": "name"
},
"id": "17852020759022520"
},
"user_has_liked": false,
"id": "1147950432085956322_185333924",
"user":
{
"username": "",
"profile_picture": "https://prifilepic.jpg",
"id": "185333924",
"full_name": "name"
}
}
}
我该如何在Java中引用“images”对象?
我尝试了以下代码:
JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject images = object.getJSONObject("images");
JSONObject image = images.getJSONObject("standard_resolution");
String url = image.getString("url");
以及这个:
JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONArray images = object.getJSONArray("images");
JSONObject standardRes = images.getJSONObject(2);
String url = standardRes.getString("url");
S是以字符串形式保存的JSON响应,如下所示:
try {
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString(); // s
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
但在这两种情况下,我都收到了“没有图像值”的错误。
images
嵌套在data
中。 - copeg