json数组在json对象中读取

时间:2018-01-29 10:47:44

标签: java android json

我正在构建一个需要下载并与在线数据库同步的Android应用程序,我将我的查询从应用程序发送到php页面,该页面以JSON格式从数据库返回相关行。

的Json

              {
                    "employee": [
                        {
                            "name": "Antoine Langlais",
                            "email": "antoine@langlais.com",
                            "department": [
                                4,
                                "Research & Development"
                            ]
                        }

java代码

                public void onResponse(String response) {
                        try {

                                    JSONObject object = new JSONObject(response);//TODO
               // 1st jsonarray     
           JSONArray empArray = object.getJSONArray("employee");
                                    Employees = new ArrayList<>();


                                    for (int i = 0; i < empArray.length(); i++) {
                                        JSONObject currentobject =empArray.getJSONObject(i);
                                        String name = currentobject.getString("name");
                                        String email = currentobject.getString("email");

//here i try to add a jsonarray to read department
 JSONArray deptArry =object.getJSONArray("department");
                                        ArrayList<String> deptt = new ArrayList<String>();
                                        for (int j = 0; j < deptArry.length(); j++) {
                                            deptt.add((String) deptArry.get(j));
                                    employee= new Employee(id,name,departement,email,phone);
                                        Employees.add(employee);
                }
                }

如何解析我的json结果? 如何更正此代码才能运行?

2 个答案:

答案 0 :(得分:0)

请更换 JSONArray deptArry =object.getJSONArray("department");JSONArray deptArry = currentobject.getJSONArray("department");

答案 1 :(得分:0)

试试这个

使用此

JSONArray deptArry = currentobject.getJSONArray("department");

而不是

JSONArray deptArry =object.getJSONArray("department");

带有外拨的代码片段

JSONArray empArray = object.getJSONArray("employee");

for (int i = 0; i < empArray.length(); i++) {

  JSONObject currentobject = empArray.getJSONObject(i);
  String name = currentobject.getString("name");
  String email = currentobject.getString("email");

  Log.i("Name", ":" + name);
  Log.i("Email", ":" + email);

  JSONArray deptArry = currentobject.getJSONArray("department");

  for (int j = 0; j < deptArry.length(); j++) {

      Log.i("Dept", ":" + deptArry.get(j));
  }

}

<强>输出

enter image description here