私は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;
}
が、両方のケースでは、私が受け取る
は、私はこれを試してみました'画像に値がありません'というエラーです。JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject data = object.getJSONObject("data");
JSONObject images = object.getJSONObject("images");
JSONObject stan_res = object.getJSONObject("standard_resolution");
String url = stan_res.getString("url");
問題は、あなたがしたいURLを取得するので、あなたが唯一持っていた、と思ったかもしれないことをあまり毛深いた:
使用しているJSONライブラリはどれですか? GSON、または単純なJSON?単純なJSON –
。私はGSONを使ってみることにしました。もしこれがうまく行かないのならば、 – Plays2
'images'が' data'の中にネストされています。 – copeg