[英]Traverse JSON data in JAVA
我是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);
}
但我的要求是,我需要获得“ 电子邮件 ”的价值。我该如何为此编码..任何建议..
在此先感谢.. Chitra
您需要首先获取items
数组,并且此数组的每个条目都包含JSONObject
,您可以从中调用getString("email")
Eg
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
仅扩展您的逻辑:
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);
JSONArray itemsArr = contactItem.getJSONArray("items");
for (int item=0 ; item < itemsArr.length() ; item++){
String email = item.getString("email");
System.out.println("Email----------"+email);
}
}
这应该工作,几乎没有调整。 我实际上没有测试它,只是在这里写手写。
您还可以使用FasterXML中的Jackson库。 您可以非常轻松地将JSON字符串转换为Java对象,然后可以使用集合上的迭代进行遍历。
如果您查看JSON字符串,它包含的items
可以被视为数组中的数组,因此,为了获得email
的价值,您需要做的就是创建另一个JSONArray
如:
JSONArray itemsArray = contactItem.getJSONArray("items");
然后,您可以通过此阵列检索email
的值
非常感谢你的时间和回应。 下面的代码做了神奇:
JSONArray responseContactData = responseContact.getJSONArray("data");
for (int i=0; i < responseContactData.length(); i++) {
String emails = contactDataValues.getJSONArray("items").getJSONObject(0).getString("email");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.