gpt4 book ai didi

java - 如何从java中的json响应中获取数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:21 26 4
gpt4 key购买 nike

我正在使用 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 中引用“图像”对象?

我试过这个:

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;
}

但在这两种情况下,我都会收到“无图像值(value)”错误。

最佳答案

images 嵌套在 data

JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject data = object.getJSONObject("data");
JSONObject images = data.getJSONObject("images");
...

关于java - 如何从java中的json响应中获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com