简体   繁体   中英

Parsing Json array from webservice to android

I am trying to parse this json data from web service to android using volley. This is the json array to be parsed.

[
 {
    "id":"1",
    "conf_room_name":"Tadoba"
 },
 {
    "id":"2",
    "conf_room_name":"Melghat"
 },
 {
    "id":"3",
    "conf_room_name":"Ranthambore"
 },
 {
    "id":"4",
    "conf_room_name":"Corbett"
 },
 {
    "id":"5",
    "conf_room_name":"Pench"
 }
]
[
 {
    "id":"1",
    "area":"Mafatlal"
 },
 {
    "id":"2",
    "area":"Andheri"
 }
]
[
 {
    "id":"1",
    "type":"Is Personal"
 },
 {
    "id":"2",
    "type":"Meeting"
 }
]

I am using this code to get the value out of my json array object ot different arraylists.

RequestQueue requestQueue2= Volley.newRequestQueue(this); // RequestQueue requestQueue3= Volley.newRequestQueue(this);

    //  Create json array request
    JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://170.241.241.198/test.php",new Response.Listener<JSONArray>(){
        public void onResponse(JSONArray jsonArray){


            for(int i=0;i<jsonArray.length();i++){
                try {
                    JSONObject jsonObject=jsonArray.getJSONObject(i);
                    stringArray_conf.add(jsonObject.getString("conf_room_name"));
                    stringArray_area.add(jsonObject.getString("area"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.e("Error", "Unable to parse json array");
        }
    });

    requestQueue2.add(jsonArrayRequest);

Only 1st array is being filled properly not the other one. I get outofboundsindex exception whenever i try using values from my 2nd arraylist.

All this happens on a button click only i want this to happen when i load my page.

Any help will be appreciated.

Make JSON as Array as below:

[
  [
    {
      "id": "1",
      "conf_room_name": "Tadoba"
    },
    {
      "id": "2",
      "conf_room_name": "Melghat"
    },
    {
      "id": "3",
      "conf_room_name": "Ranthambore"
    },
    {
      "id": "4",
      "conf_room_name": "Corbett"
    },
    {
      "id": "5",
      "conf_room_name": "Pench"
    }
  ],
  [
    {
      "id": "1",
      "area": "Mafatlal"
    },
    {
      "id": "2",
      "area": "Andheri"
    }
  ],
  [
    {
      "id": "1",
      "type": "Is Personal"
    },
    {
      "id": "2",
      "type": "Meeting"
    }
  ]
]

Or Object (easier to reading and understanding):

{
  "rooms": [
    {
      "id": "1",
      "conf_room_name": "Tadoba"
    },
    {
      "id": "2",
      "conf_room_name": "Melghat"
    },
    {
      "id": "3",
      "conf_room_name": "Ranthambore"
    },
    {
      "id": "4",
      "conf_room_name": "Corbett"
    },
    {
      "id": "5",
      "conf_room_name": "Pench"
    }
  ],
  "areas": [
    {
      "id": "1",
      "area": "Mafatlal"
    },
    {
      "id": "2",
      "area": "Andheri"
    }
  ],
  "types": [
    {
      "id": "1",
      "type": "Is Personal"
    },
    {
      "id": "2",
      "type": "Meeting"
    }
  ]
}

PHP code maybe like below:

<?php

$sqlroom = mysql_query("SELECT * FROM `room_table`");
$room_rows = array();
while($r = mysql_fetch_assoc($sqlroom)) {
  $room_rows[] = $r;
}

$sqlarea = mysql_query("SELECT * FROM `area_table`");
$area_rows = array();
while($r = mysql_fetch_assoc($sqlarea)) {
  $area_rows[] = $r;
}

$sqltype = mysql_query("SELECT * FROM `type_table`");
$type_rows = array();
while($r = mysql_fetch_assoc($sqltype)) {
  $type_rows[] = $r;
}

$result = array();
$result["rooms"] = $room_rows;
$result["areas"] = $area_rows;
$result["types"] = $type_rows;

echo json_encode($result);

?>

You seem to be trying to parse three different types of data: conference rooms, areas (which presumably contain conference rooms?) and some information about either one (although it's not clear which). It therefore doesn't make sense to try and store these in a single array as each element contains a different data structure compared to the other two.

If the type is a description of one of the other two objects then it should be compassed within that object, not treated as a separate one. A room doesn't necessarily have to sit within an area but it might also make sense to have it there.

You say you are " pulling all these values from a mysql server and then using php to encode the json data which gives me the structure of the json array " which implies you do not have direct access to the JSON structure, but you should still have access to the PHP structure. The JSON encoder will use the design of the PHP array / object to structure the JSON so, for this to work you need to create more-or-less matching PHP and Java objects at either end of the serialization process.

For instance:

$obj = (object) array
  ('id' => '1', 'area' => 'Mafatlal', 'rooms' => array
    ('id' => '1', 'conf_room_name' => 'Tadoba', 'type' => 'Is Personal'),
    ...
  ('id' => '2', 'area' => 'Andheri', 'rooms' => array...
  );

and

public class Area {
    private int id;
    private String area;
    private Room[] rooms;

}

public class Room {
    private int id;
    private String conf_room_name;
    private String type;
}

Note that, in contrast to the usual Java camel-case naming convention, object variables will usually have to match the incoming JSON variable name (ie: conf_room_name instead of confRoomName ).

You need to add values using for loop.

        for(int i=0;i<jsonArray.length();i++){
            try {
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                if(jsonObject.toString.contains("conf_room_name"))
                  stringArray_conf.add(jsonObject.getString("conf_room_name"));
                else if(jsonObject.toString.contains("area"))
                  stringArray_area.add(jsonObject.getString("area"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM