lulu
lulu

Reputation: 177

Extracting JSON fields using java

I am trying to extract a person's details who liked a facebook page by passing the page id as parameter. I extracted the JSON content of that page and now from that I want to extract name and id of users.

How do I achieve that ?

Code:

JSONObject json = readurl("https://graph.facebook.com/pageid");
System.out.println(json.toString());
System.out.println("Page id is:"+json.get("id"));

JSON:

"likes":{
"data":[
    {
        "id":"*******",
        "name":"vv"
    },
    {
        "id":"********",
        "name":"abc"
    },

Upvotes: 2

Views: 36254

Answers (3)

trylimits
trylimits

Reputation: 2575

This snippet is not tested, but I'm pretty sure it works:

JSONArray data = json.getJSONArray("data");
for (int i=0; i < data.length(); i++) {
    JSONObject o = data.getJSONObject(i);
    sysout(o.getString("id");
    sysout(o.getString("name");
}

Upvotes: 2

Pradeep Simha
Pradeep Simha

Reputation: 18123

Code like this would do the trick.

JSONObject json = readurl("https://graph.facebook.com/pageid");
JSONArray dataJsonArray = json.getJSONArray("data");
for(int i=0; i<dataJsonArray.length; i++) {
   JSONObject dataObj = dataJsonArray.get(i);
   String id = dataObj.getString("id");
   //Similarly you can extract for other fields.
}

Basically data is a JSONArray since it starts with [. So simply get would not work, you must use JSONArray.

Note: I haven't compiled this code, but I think I gave you idea to proceed. Also refer this link to get hold of basics of parsing JSON in java.

Upvotes: 2

Thom
Thom

Reputation: 15062

I use google's Gson library from: https://code.google.com/p/google-gson/

Upvotes: 0

Related Questions