0

Possible Duplicate:
JSON Parsing in Android

As I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:

{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}

Can anyone help me how to do this?

Community
  • 1
  • 1
krinn
  • 882
  • 2
  • 10
  • 16
  • Remember that {} is JSONObjects, and [] is JSONArrays. It's simply a matter of understanding the JSON structure and then extracting the different arrays/objects from it. – DecodeGnome Jun 25 '12 at 09:38
  • i use this grate [tutorial](http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html) to learn how to work with Gson, hope it also helps you :-) – Boe-Dev Jun 25 '12 at 09:35

3 Answers3

1
      //Model class 

    class Model {

         private  String mId ;
          private   String mScore;

         public Model (String id , String score){

             mId = id ;
             mScore= score
         }


      //getter and setter 

    } 

// in your class

    private ArrayLsit getLsit(String str){
      ArrayLsit<Model > list = new  ArrayLsit<Model>();

        // getting JSON string from URL
        JSONObject json = new JSONObject(str);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray("data");

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString("id");
                String score= c.getString("score");
                list.add(new Model(id ,score))

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

   return list

 }
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

Check out the code..

        Result = jsonObject.getString("data");

        jsonArray = new JSONArray(Result);
        for (int i = 0; i < jsonArray.length(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            try {
                jsonObject.getString("Id");

            } catch (Exception ex) {
                cafeandbarsList.add(null);
                ex.printStackTrace();
            }
        }

Thanks

Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
0

create to class for json,

Gson gson = new Gson(); Jsondata jsonddata = gson.fromJson(response, Jsondata .class);

===== JsonData.jave

@SerializedName("selected_id")
public String sid;

    @SerializedName("data") 
public List<data> dalalist;

=== data.java

    @SerializedName("id")
public String id;

    @SerializedName("score")
public String score;
Ankitkumar Makwana
  • 3,475
  • 3
  • 19
  • 45