我正在使用instagram REST API,我需要從JSON響應中抓取圖像鏈接。如何從java中的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?
我嘗試這樣做:
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;
}
但在這兩種情況下,我收到一個'圖像沒有價值'的錯誤。
你正在使用哪個JSON庫? GSON,還是簡單的JSON? –
簡單的JSON。我即將嘗試使用GSON,如果我無法解決這個問題 – Plays2
'圖像'嵌套在'data'內 – copeg