如何从java中的json响应中获取数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何从java中的json响应中获取数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2241字,纯文字阅读大概需要4分钟。
内容图文
![如何从java中的json响应中获取数组](/upload/InfoBanner/zyjiaocheng/734/8545117d44534057809e7f9dc43516d2.jpg)
我正在使用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;
}
但是在这两种情况下我都收到了“没有图像值”的错误.
解决方法:
图像嵌套在数据中
JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject data = object.getJSONObject("data");
JSONObject images = data.getJSONObject("images");
...
内容总结
以上是互联网集市为您收集整理的如何从java中的json响应中获取数组全部内容,希望文章能够帮你解决如何从java中的json响应中获取数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。