遍历JAVA中的JSON数据

我是
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
点赞