Native Nerd
Native Nerd

Reputation: 154

Android JSON parsing arrays with GSON

I've been fighting with GSON for the better part of the day. Well, not the GSON so much as my general non-understanding of lists in Android I think. Basically what is happening is I am receiving 2 arrays in JSON, which will then each be formatted and displayed in a list:

Adventures:
+-------------+
| Adventure 1 |
+-------------+
| Adventure 2 |
+-------------+
Events:
+-------------+
|   Event 1   |
+-------------+
|   Event 2   |
+-------------+

I'm able to read out individual string just fine, but I'm not getting my head around moving this on to arrays. JSON format I'm recieving is:

{
"events": [
    {
        "eid": "11111111",
        "bid": "aaaaaaaa",
        "bname": "Example Business 1",
        "start": "3/26/14 @ 6pm",
        "end": "3/27/14 @ 2am",
        "points": "50",
        "title": "Example Event 1",
        "description": "Example Event Description",
        "cat": "Nightlife",
        "type": "Bar",
        "subtype": "Karaoke",
        "valid": true
    },
    {
        "eid": "22222222",
        "bid": "bbbbbbbb",
        "bname": "Example Business 2",
        "start": "3/26/14 @ 6pm",
        "end": "3/27/14 @ 2am",
        "points": "50",
        "title": "Example Event 2",
        "description": "Example Event Description",
        "cat": "Nightlife",
        "type": "Comedy",
        "subtype": "General",
        "valid": true
    },
    {
        "eid": "33333333",
        "bid": "cccccccc",
        "bname": "Example Business 3",
        "start": "3/26/14 @ 6pm",
        "end": "3/27/14 @ 2am",
        "points": "150",
        "title": "Example Event 3",
        "description": "Example Event Description",
        "cat": "Dining",
        "type": "Restraunt",
        "subtype": "Chinese",
        "valid": true
    }
],
"adventures": [
    {
        "aid": "11111111",
        "bid": "aaaaaaaa",
        "start": "3/26/14 6pm",
        "end": "3/27/14 2am",
        "points": "150",
        "title": "Example Adventure 1",
        "description": "Example Adventure Description",
        "cat": "Nightlife",
        "type": "Bar",
        "subtype": "Karaoke",
        "steps_comp": "2",
        "total_steps": "5",
        "valid": true
    },
    {
        "aid": "22222222",
        "bid": "bbbbbbbb",
        "start": "3/26/14 6pm",
        "end": "3/27/14 2am",
        "points": "250",
        "title": "Example Adventure 2",
        "description": "Example Adventure Description",
        "cat": "Nightlife",
        "type": "Bar",
        "subtype": "Neighborhood",
        "steps_comp": "0",
        "total_steps": "5",
        "valid": true
    }
]

}

I'm parsing out the JSON with the following (Volley code included):

RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, full_url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            String example = response.toString();
            Log.e("JSON Response", example);

            try {
                JsonParser jsonParser = new JsonParser();
                JsonObject jo = (JsonObject)jsonParser.parse(example);
                JsonArray jsonArr = jo.getAsJsonArray("events");
                //jsonArr.
                Gson googleJson = new Gson();
                ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);

                System.out.println("List size is : "+jsonObjList.size());
                System.out.println("List Elements are  : "+jsonObjList.toString());

                for (int i = 0; i < jsonObjList.size(); i++){
                       String item = jsonObjList.get(i).toString();
                       System.out.println("Item " + i + " : " + item);
                }

                Toast.makeText(getApplicationContext(), "0: "+jsonObjList.get(0),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Toast.makeText(getApplicationContext(), "blah",
               Toast.LENGTH_LONG).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO Auto-generated method stub
        }
    }
);
queue.add(jsObjRequest);

I'm getting each row just fine, but it's just a string so I'm not able to get at the individual elements for each. I'm thinking I might need to do another GSON call inside the for loop to break that one as well, then place inside of a array? This seems messy. I've done a bit of googleing(how I've gotten this far), but I can't seem to put the pieces together to make this one work. Any help would be appreciated.

Upvotes: 1

Views: 4141

Answers (4)

Amit Gupta
Amit Gupta

Reputation: 8939

First create class for each JsonAarry to hold the vales

public class Events {
    private String eid;
    private String bid;
    private String bname;
    private String start;
    private String end;
    private String points;
    private String title;
    private String description;
    private String cat;
    private String type;
    private String subtype;
    private boolean valid;
    @Override
    public String toString() {
        return "Events [eid=" + eid + ", bid=" + bid + ", bname=" + bname
                + ", start=" + start + ", end=" + end + ", points=" + points
                + ", title=" + title + ", description=" + description
                + ", cat=" + cat + ", type=" + type + ", subtype=" + subtype
                + ", valid=" + valid + "]";
    }

}

and

public class Adventures {
    private String aid;
    private String bid;
    private String start;
    private String end;
    private String points;
    private String title;
    private String description;
    private String cat;
    private String type;
    private String subtype;
    private String steps_comp;
    @Override
    public String toString() {
        return "Adventures [aid=" + aid + ", bid=" + bid + ", start=" + start
                + ", end=" + end + ", points=" + points + ", title=" + title
                + ", description=" + description + ", cat=" + cat + ", type="
                + type + ", subtype=" + subtype + ", steps_comp=" + steps_comp
                + ", total_steps=" + total_steps + ", valid=" + valid + "]";
    }
    private String total_steps;
    private boolean valid;

}

Now create a class that hold the whole response

public class ResponseHolder {
    private ArrayList<Events> events;
    private ArrayList<Adventures> adventures;
    @Override
    public String toString() {
        return "ResponseHolder [events=" + events + ", adventures="
                + adventures + "]";
    }
    public ArrayList<Events> getEvents() {
        return events;
    }
    public ArrayList<Adventures> getAdventures() {
        return adventures;
    }
}

and finally

Gson googleJson = new Gson();
ResponseHolder rh= googleJson.fromJson(jsonArr, ResponseHolder.class);

And get the data like

        for(Events e: rh.getEvents()){
            System.out.println(e.toString());
        }

        for(Adventures e: rh.getAdventures()){
            System.out.println(e.toString());
        }

Upvotes: 5

user3283148
user3283148

Reputation: 111

        I have same problem. and i have json like this.

            {
                "latest_posting": [
                    {
                        "posting_id": "7",
                        "posting_title": "Ring",
                        "photo_img": "images/posting/IMG_12121212.png.png",
                        "normal_price": null
                    },
                    {
                        "posting_id": "8",
                        "posting_title": "dsadsd",
                        "photo_img": "images/posting/IMG_1212121216.jpg",
                        "normal_price": null
                    },
                    {
                        "posting_id": "9",
                        "posting_title": "dasd",
                        "photo_img": "images/posting/IMG_121212122.png",
                        "normal_price": null
                    }
                ],
                "promotion_litsing": [
                    {
                        "posting_id": "10",
                        "posting_title": "dasd",
                        "photo_img": "images/posting/IMG_121212123.png",
                        "normal_price": null
                    }
                ]
            }

        you said that 
        JsonResponse jsonObjList = googleJson.fromJson(jsonArr, JsonResponse .class);


        But we have two array in data set class right which "jsonArr" we pass for parsing. 

        to get each of separate response of array in log.

        My data set class




        public class BannerAdvertismentVO implements Serializable {

            private ArrayList<NormalPostingVO> promotion_listing;


            private ArrayList<NormalPostingVO> latest_posting ;


            public ArrayList<NormalPostingVO> getPromotion_listing() {
                return promotion_listing;
            }


            public void setPromotion_listing(ArrayList<NormalPostingVO> promotion_listing) {
                this.promotion_listing = promotion_listing;
            }


            public ArrayList<NormalPostingVO> getLatest_posting() {
                return latest_posting;
            }


            public void setLatest_posting(ArrayList<NormalPostingVO> latest_posting) {
                this.latest_posting = latest_posting;
            }



        }





 private String posting_id;
    private String posting_title;
    private String photo_img;
    private String normal_price;



    public String getPosting_id() {
        return posting_id;
    }
    public void setPosting_id(String posting_id) {
        this.posting_id = posting_id;
    }
    public String getPosting_title() {
        return posting_title;
    }
    public void setPosting_title(String posting_title) {
        this.posting_title = posting_title;
    }
    public String getNormal_price() {
        return normal_price;
    }
    public void setNormal_price(String normal_price) {
        this.normal_price = normal_price;
    }
    public String getPhoto_img() {
        return photo_img;
    }
    public void setPhoto_img(String photo_img) {
        this.photo_img = photo_img;
    }
    my parser class

    public static BannerAdvertismentVO parseBannerAdvertismentData(String response){

            BannerAdvertismentVO banner  =null;
             Gson Json;

            try {
                JSONObject jsonObject = new JSONObject(response);

                Json = new GsonBuilder().create();

                banner = Json.fromJson(jsonObject.toString(), BannerAdvertismentVO .class);

                Log.e("", "LOG1==" + banner.getLatest_posting() +"/n"+ banner.getPromotion_listing());



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




            return banner;
        }

this show me null->banner.getPromotion_listing();

Upvotes: 0

Ondřej Z
Ondřej Z

Reputation: 5174

Create Java object for each of your json objects. For example:

public class Event {

  private String bid;
  private int eid;

}

public class Adventure {
    private String bid;
    private int eid;
 // rest of the fields
}

Then, create a class that contains these objects:

public class JsonResponse {
  private ArrayList<Event> events;
  private ArrayList<Adventure> adventures;
}

In your code, you should be able to deserialize as follows:

Gson googleJson = new Gson();
JsonResponse jsonObjList = googleJson.fromJson(jsonArr, JsonResponse .class);

Upvotes: 1

Karthick pop
Karthick pop

Reputation: 616

I cant get you but i think you are struggling in how to get each value from the jsonarray, if so you this code in your for loop

 jsonobject = jsonArr.getJSONObject(i);
  if (jsonobject != null) 
   {
   String ID= jsonobject.getString("eid");
   String BID= jsonobject.getString("bid");

 // Like this implement for other jsonobjects

    }

Upvotes: 0

Related Questions