首页 / JSON / 遍历JAVA中的JSON数据
遍历JAVA中的JSON数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了遍历JAVA中的JSON数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1844字,纯文字阅读大概需要3分钟。
内容图文
![遍历JAVA中的JSON数据](/upload/InfoBanner/zyjiaocheng/779/aaf05a6f4a0040ceb1ee01ef19599dbb.jpg)
我是JSON的新手.我使用HTTPUrlConnections并在JAVA程序中获得一些响应.响应数据将是,
{
"data": [
{
"id": 1,
"userId": 1,
"name": "ABC",
"modified": "2014-12-04",
"created": "2014-12-04",
"items": [
{
"email": "abc@gmail.com",
"links": [
{
.
.
.
.
}
]
}
]
}
]
}
从这个响应中我可以使用下面的java代码获取“name”字段的值.
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
}
但我的要求是,我需要获得“电子邮件”的价值.我该怎么编码呢?
任何建议..
提前致谢..
奇特拉
解决方法:
您需要首先获取items数组,并且此数组的每个条目都包含JSONObject,您可以从中调用getString(“email”).E.g.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc@gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
产量
abc@gmail.com
Name----------ABC
内容总结
以上是互联网集市为您收集整理的遍历JAVA中的JSON数据全部内容,希望文章能够帮你解决遍历JAVA中的JSON数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。