java - 在java/Android中解析JSON

标签 java android json

我有这种格式的代码。谁能帮助我如何读取数组?我需要读取联系人数组。

 {
  "success": true,
  "contacts": [
  {
  "username": "ceema",
  "profile": {
    "name": "Ceema S",
    "email": "ceemas@gmail.com",
    "address": "No 143, gangaeyam, Maikkad P O, Kerala",
    "phone": {
      "mobile": "3333",
      "home": "2222",
      "office": "6666"
    }
  }
},
{
  "username": "hari",
  "profile": {
    "name": "Harikrishnan V S",
    "email": "harikriii@gmail.com",
    "address": "No 143, harihome, Maikkad P O, Kerala",
    "phone": {
      "mobile": "3333",
      "home": "2222",
      "office": "6666"
    }
  }
},
{
  "username": "pranav",
  "profile": {
    "name": "Pranav Mohan",
    "email": "pranavmohan@gmail.com",
    "address": "No 143, harihome, Maikkad P O, Kerala",
    "phone": {
      "mobile": "3333",
      "home": "2222",
      "office": "6666"
    }
  }
}
]
}

我尝试过:

if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    //String id = c.getString(TAG_NAME);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    //String gender = c.getString(TAG_GENDER);

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject(TAG_PHONE);
                    String mobile = phone.getString(TAG_PHONE_MOBILE);
                    String home = phone.getString(TAG_PHONE_HOME);
                    String office = phone.getString(TAG_PHONE_OFFICE);

这个jsonstr是来自网站的json响应。 我需要读取嵌套的联系人并将其填充到

最佳答案

This jsonstr is json response from the site. I need to read the nested contacts and populate it to

你几乎猜对了。您正在寻找的对象在个人资料内

JSONObject c = contacts.getJSONObject(i);
JSONObject profile = c.getJSONObject("profile");

并使用profile而不是c来查看姓名、电话等

关于java - 在java/Android中解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32520959/

相关文章:

java - 发送命令后建立套接字连接等待响应

jquery - ASP MVC JsonResult 呈现为页面,而不是通过调用 jQuery 函数捕获

java - Android - 单击按钮获取 ListView 中的 EditText 值的总和

java - 我的 EmployeeStore 中的 MainApp 出现错误

java - 如何在静态上下文中将泛型类与特定对象一起使用?

java - 如何在 power mock 中为 org.asynchttpclient.AsyncHttpClient 创建模拟对象

java - 安卓错误: IllegalStateException

javascript - 使用 Angular.js 显示 JsonResult

json - 无法使用 Rustc-serialize 处理 JSON 中的可选字段

java - 获取 "success"而没有收到任何 GCM 消息