CodeMonkey
CodeMonkey

Reputation: 2285

Parsing JSON using Gson library for JAVA

I am working on parsing a JSON in JAVA which has a structure like this,

{
  "id": "P410R",
  "create_time": "2014-05-29T19:21:34Z",
  "update_time": "2014-05-29T19:21:34Z",
  "state": "created",
  "links": [
    {
      "href": "url1",
      "rel": "self",
      "method": "GET"
    },
    {
      "href": "url2",
      "rel": "approval_url",
      "method": "REDIRECT"
    },
    {
      "href": "url3",
      "rel": "execute",
      "method": "POST"
    }
  ]
}

I need to obtain links.href where rel = "approval_url"

So far i have been into nested data structure declarations and can not reach to links.href. I am using GSON library and here is what my code looks like:

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonResult, JsonElement.class); //jsonResult is class object


JsonObject jsonObj = element.getAsJsonObject();
    Map jsonJavaRootObject = new Gson().fromJson(jsonObj, Map.class);
    ArrayList refUrls = (ArrayList) jsonJavaRootObject.get("links");

//  Map gsonStrMap = new Gson().from .fromJson(refUrls.get(1), Map.class);

    String result = jsonJavaRootObject.get("links").toString();
    //JsonObject jsonObjRefUrl = (JsonObject) refUrls.get(1);

Upvotes: 0

Views: 784

Answers (2)

matt
matt

Reputation: 115

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonResult, JsonElement.class); //jsonResult is class object
JsonObject jsonObj = element.getAsJsonObject();
JsonArray links = jsonObj.get("links").getAsJsonArray();
for (JsonElement item : links) {
   if (item.getAsJsonObject().get("rel").toString().equals("\"approval_url\"") {
      // match
   }
}

Upvotes: 0

Braj
Braj

Reputation: 46841

This is the simple solution using Map<String, Object> if you are interested to single value only. Even though it can be achieved using Plain POJO class as well.

Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>() {}.getType();

Map<String, Object> data = gson.fromJson(json, type);
ArrayList<Map<String, String>> list = (ArrayList<Map<String, String>>) (data.get("links"));
for (Map<String, String> map : list) {
    if (map.get("rel").equals("approval_url")) {
        System.out.println(map.get("href"));
        break;
    }
}

Here is the solution with JAVA plain POJO class if you are interested to links only.

class Links{
    private ArrayList<Link> links;
    // getter & setter
}

class Link {
    private String href;
    private String rel;
    private String method;
   // getter & setter
}

Gson gson = new Gson();
Links links = gson.fromJson(json, Links.class);

for(Link link:links.getLinks()){
    if(link.getRel().equals("approval_url")){
        System.out.println(link.getHref());
        break;
    }
}

Upvotes: 2

Related Questions