如何使用volley库解析android中的嵌套json数组

时间:2022-01-05 08:22:26

I have nested json array in below format.I am using volley liabrary for JSON Parsing.

我在下面的格式中嵌套了json数组。我正在使用volley liabrary进行JSON解析。

{
"City": [{
        "name": "Mumbai",
        "Mumbai": [{
            "area": "andheri",

            "diler": [{
                "DName": "yuvraj"
            }]
        }, {
            "area": "jogeshwari"
        }, {
            "area": "goregaon"
        }]
    },

    {

        "name": "Nashik",
        "Nashik": [{
            "area": "clg rd",
            "diler": [{
                "DName": "yuvraj"
            }]
        }, {
            "area": "GP RD",
            "diler": [{
                "DName": "Roshan"
            }]
        }, {
            "area": "CBS",
            "diler": [{
                "DName": "Deepak"
            }]
        }]

    }, {
        "name": "Bengaluru"
    }
]}

Below is the code which i have write in android.

下面是我在android中编写的代码。

   jsonURL = "http://192.168.1.11/cycle_webservices/testing.json";

    buttonReq.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                    jsonURL,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            try {
                                for (int i = 0; i < response.length(); i++) {
                                    JSONObject jsonObject = response.getJSONObject(i);
                                    String name = jsonObject.getString("name");
                                    String area = jsonObject.getString("area");
                                    String diler = jsonObject.getString("diler");

                                    textView.append("\nCity: " + name + "\nArea: " + area + "\nDealer: " + diler +   "\n");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("VOLLEY", "ERROR");
                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
            );
            requestQueue.add(jsonArrayRequest);
        }
    });

But i am getting Errors while parsing it in Android. The error is- JSONObject can not be converted to JSONArray

但是我在Android中解析时遇到了错误。错误是 - JSONObject无法转换为JSONArray

Can anyone please provide sample code to parse this json Array.

任何人都可以提供示例代码来解析这个json数组。

Thanks in Advance

提前致谢

4 个解决方案

#1


4  

Here is your problem solution, use below code

这是您的问题解决方案,使用下面的代码

 try {
        JSONObject jsonObject = new JSONObject("response");
        JSONArray jsonArray = jsonObject.getJSONArray("City");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String name = object.getString("name");
            if (object.length() != 0) {
                Iterator<String> key = object.keys();
                while (key.hasNext()) {
                    String cityname = key.next();
                    JSONArray ja = object.getJSONArray(cityname);
                    for (int j = 0; j < ja.length(); j++) {
                        JSONObject object1 = ja.getJSONObject(j);
                        String area = object1.getString("area");

                    }
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

And try to make your JSON format same.

并尝试使您的JSON格式相同。

#2


3  

The point is the first json node is a JsonObject, change your code this way and continue parsing:

关键是第一个json节点是JsonObject,以这种方式更改代码并继续解析:

new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) { 

#3


1  

Use JSONObject for parsing data like:

使用JSONObject解析数据,如:

  JSONObject jsonObject = new JSONObject(response);

  JSONArray jsonArray = jsonObject.getJSONArray("City");

  for(int i = 0; i<jsonArray.length(); i++)
  {
      JSONObject jsonObject = jsonArray .getJSONObject(i);

      String name = jsonObject.getString("name");

      JSONArray city_array = jsonObject.getJSONArray(name);

      for(int j=0; j<city_array.length(); j++)
      {
          JSONObject obj = city_array.getJSONObject(j);

          String area = obj.getString("area");

          JSONArray diler_array = obj.getJSONArray("diler");

          JSONObject obj1 = diler_array.getJSONObject(0);

          String DName = obj1.getString("DName");
      }
  }

Please check edited answer.

请检查编辑的答案。

#4


0  

pass data array inside array in android using volley

使用volley在android中的数组内传递数据数组

public List<HashMap<String,String>> returnJsonforPhp(){
  HashMap<String,String> map = new HashMap<String,String>();
  List<HashMap<String,String>> forjson= new ArrayList<HashMap<String,String>>();
  /*for(int i=0;i<dblist;i++) {
    map.put("name",dblist.getName());
    map.put("email",dblist.getEmail());
    map.put("mobno",dblist.getMobno());
    forjson.add(map);
  }*/

  map.put("name","ravi");
  map.put("email","ravi@gmail.com");
  map.put("mobno","9897939595");
  forjson.add(map);
  return forjson;
}

String OTP_Url = "https://www.yourdomain.com/rest/updateregistration/";

String OTP_Url =“https://www.yourdomain.com/rest/updateregistration/”;

public String getJson() throws JsonProcessingException {

public String getJson()抛出JsonProcessingException {

List> list = new ArrayList>(); List>> newlist = new ArrayList>>(); newlist.add(list);

List> list = new ArrayList>(); List >> newlist = new ArrayList >>(); newlist.add(列表);

    HashMap<String,String> map = new HashMap<String, String>();
    map.put("name","knnkl");
    map.put("email","kjbjbk");
    map.put("password","njnjknk");

    list.add(map);
    newlist.add(list);
    String parsedJson = new ObjectMapper().writeValueAsString(newlist);//json conversion
    return parsedJson;
}

compile ( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1'] )

compile([group:'com.fasterxml.jackson.core',name:'jackson-core',version:'2.4.1'],[group:'com.fasterxml.jackson.core',name:'jackson- annotations',version:'2.4.1'],[group:'com.fasterxml.jackson.core',name:'jackson-databind',version:'2.4.1'])

#1


4  

Here is your problem solution, use below code

这是您的问题解决方案,使用下面的代码

 try {
        JSONObject jsonObject = new JSONObject("response");
        JSONArray jsonArray = jsonObject.getJSONArray("City");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String name = object.getString("name");
            if (object.length() != 0) {
                Iterator<String> key = object.keys();
                while (key.hasNext()) {
                    String cityname = key.next();
                    JSONArray ja = object.getJSONArray(cityname);
                    for (int j = 0; j < ja.length(); j++) {
                        JSONObject object1 = ja.getJSONObject(j);
                        String area = object1.getString("area");

                    }
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

And try to make your JSON format same.

并尝试使您的JSON格式相同。

#2


3  

The point is the first json node is a JsonObject, change your code this way and continue parsing:

关键是第一个json节点是JsonObject,以这种方式更改代码并继续解析:

new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) { 

#3


1  

Use JSONObject for parsing data like:

使用JSONObject解析数据,如:

  JSONObject jsonObject = new JSONObject(response);

  JSONArray jsonArray = jsonObject.getJSONArray("City");

  for(int i = 0; i<jsonArray.length(); i++)
  {
      JSONObject jsonObject = jsonArray .getJSONObject(i);

      String name = jsonObject.getString("name");

      JSONArray city_array = jsonObject.getJSONArray(name);

      for(int j=0; j<city_array.length(); j++)
      {
          JSONObject obj = city_array.getJSONObject(j);

          String area = obj.getString("area");

          JSONArray diler_array = obj.getJSONArray("diler");

          JSONObject obj1 = diler_array.getJSONObject(0);

          String DName = obj1.getString("DName");
      }
  }

Please check edited answer.

请检查编辑的答案。

#4


0  

pass data array inside array in android using volley

使用volley在android中的数组内传递数据数组

public List<HashMap<String,String>> returnJsonforPhp(){
  HashMap<String,String> map = new HashMap<String,String>();
  List<HashMap<String,String>> forjson= new ArrayList<HashMap<String,String>>();
  /*for(int i=0;i<dblist;i++) {
    map.put("name",dblist.getName());
    map.put("email",dblist.getEmail());
    map.put("mobno",dblist.getMobno());
    forjson.add(map);
  }*/

  map.put("name","ravi");
  map.put("email","ravi@gmail.com");
  map.put("mobno","9897939595");
  forjson.add(map);
  return forjson;
}

String OTP_Url = "https://www.yourdomain.com/rest/updateregistration/";

String OTP_Url =“https://www.yourdomain.com/rest/updateregistration/”;

public String getJson() throws JsonProcessingException {

public String getJson()抛出JsonProcessingException {

List> list = new ArrayList>(); List>> newlist = new ArrayList>>(); newlist.add(list);

List> list = new ArrayList>(); List >> newlist = new ArrayList >>(); newlist.add(列表);

    HashMap<String,String> map = new HashMap<String, String>();
    map.put("name","knnkl");
    map.put("email","kjbjbk");
    map.put("password","njnjknk");

    list.add(map);
    newlist.add(list);
    String parsedJson = new ObjectMapper().writeValueAsString(newlist);//json conversion
    return parsedJson;
}

compile ( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1'] )

compile([group:'com.fasterxml.jackson.core',name:'jackson-core',version:'2.4.1'],[group:'com.fasterxml.jackson.core',name:'jackson- annotations',version:'2.4.1'],[group:'com.fasterxml.jackson.core',name:'jackson-databind',version:'2.4.1'])