0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Saty
  • 2,563
  • 3
  • 37
  • 88
  • possible duplicate of [JSON Array iteration in Android/Java](http://stackoverflow.com/questions/3408985/json-array-iteration-in-android-java) – glycerin Aug 19 '14 at 15:15

2 Answers2

2

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
}
mittelmania
  • 3,393
  • 4
  • 23
  • 48
0

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;
 }
 //.....
}
MHP
  • 2,613
  • 1
  • 16
  • 26