java遍历json,在JAVA中遍历JSON数据

"这篇博客介绍了如何在Java程序中解析JSON响应以获取电子邮件字段的值。通过使用org.json库,首先获取到JSON对象的"data"数组,然后遍历每个条目,再获取每个条目中的"items"数组,最后从中提取出"email"字段。"
摘要由CSDN通过智能技术生成

I am new to JSON..Am using HTTPUrlConnections and getting some response in JAVA program.The response data will be like,

{

"data": [

{

"id": 1,

"userId": 1,

"name": "ABC",

"modified": "2014-12-04",

"created": "2014-12-04",

"items": [

{

"email": "abc@gmail.com",

"links": [

{

.

.

.

.

}

]

}

]

}

]

}

From this response am able to get the value of "name" field with the below java code.

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

}

But my requirement is,I need to get the value of "email" ..How should I code for that..

Any advice..

Thanks in advance..

Chitra

解决方案

You need to first get the items array and each entry of this array contains JSONObject, from which you can call 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);

}

}

}

Output

abc@gmail.com

Name----------ABC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值