简体   繁体   中英

Parsing json array from the JSON object in Android

I am trying to parse a JSON array from a string which I receive from the server.

Example of the array is

{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}

I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List

     JSONObject o = new JSONObject(result.toString());
     JSONArray slideContent = (JSONArray) o.get("data");
     Iterator i = ((List<NameValuePair>) slideContent).iterator();
     while (i.hasNext()) {
                     JSONObject slide = (JSONObject) i.next();
                     int title = (Integer)slide.get("id");
                     String Status = (String)slide.get("status");
                     String name = (String)slide.get("name");
                     String number = (String)slide.get("number");
                     Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
                    // System.out.println(title);
                 }

What should be the correct way of parsing it?

It makes sense as a JSONArray cannot be cast to a List<> , nor does it have an iterator. JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.

So, considering all these, you may wish to write something like this:

JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");

for(int i = 0 ; i < slideContent.length() ; i++) {
    int title = slideContent.getInt("id");
    String Status = slideContent.getString("status");
    // Get your other values here
}

you should do like this:

JSONObject o = new JSONObject(result.toString());  
JSONArray array = jsonObject.getJSONArray("data");  
JSONObject jtemp ;  
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;

    for(int i=0;i<array.length();i++)
    {
        mData = new MData();
        jtemp = array.getJSONObject(i);  //get i record of your array
        //do some thing with this like  
        String id = jtemp.getString("id"); 
        mData.setId(Integer.parseInt(id));
        ///and other details  
        dataArray.put(mData);  
   }  

and MData.class

class MData{
  private int id;
  /....

 public void setId(int id){
     this.id = id;
 }
 //.....
}

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