Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON data specifically using GraphQl

I am trying to Parse JSON data using retrofit but I am using GraphQL as my API. Attached is an example of the data that I am trying to parse. I tried following the tutorial from this link: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ but the JSON data that he is pulling from is from a REST API.

Here is the GraphQL data:

 {
 "data": {
"allEvents": {
  "edges": [
    {
      "node": {
        "title": "UWB Weekly Meeting"
      }
    },
    {
      "node": {
        "title": "Startup Weekly"
      }
    },
    {
      "node": {
        "title": "Microsoft Capstone Opportunity"
      }
    },
    {
      "node": {
        "title": "UWB Camp Kickoff"
      }
    },
    {
      "node": {
        "title": "Agusto's Winter Event"
      }
    }
  ]
}

} }

like image 982
A Trivedi Avatar asked Dec 19 '25 00:12

A Trivedi


1 Answers

First, you need a POJO (plain old Java class) with the structure that you're expecting in the JSON response. Let's call it Event. From your example, it has a title so that's the class that we need:

public class Event {
    private String id;
    private String title;

    public Event() {

    }

    public Event(String id, String title) {
        this.id = id;
        this.title = title;
    }

    @Override
    public String toString() {
        return "Event{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                '}';
    }

    public String getId() {
      return id;
    }

    public String getTitle() {
        return title;
    }

}

Then you can use the Gson library to parse the response JSON to a list of Event objects:

Gson gson = new Gson();
try {
    JSONArray jsonEvents = new JSONObject(body).getJSONObject("data").getJSONObject("allEvents").getJSONArray("edges");
    for (int i = 0; i < jsonEvents.length(); ++i) {
        JSONObject event = jsonEvents.getJSONObject(i).getJSONObject("node");
        Log.v("TAG", gson.fromJson(event.toString(), Event.class).toString());
    }
} catch (JSONException e) {
    e.printStackTrace();
}

You can find a complete example here.

like image 167
marktani Avatar answered Dec 20 '25 18:12

marktani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!