使用GSON库为JAVA解析JSON

时间:2014-05-30 18:50:09

标签: java json gson

我正在解析JAVA中的JSON,它有一个像这样的结构,

{
  "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"
    }
  ]
}

我需要获取links.href,其中rel =“approval_url”

到目前为止,我已经进入嵌套数据结构声明,无法访问links.href。我正在使用GSON库,这是我的代码:

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);

2 个答案:

答案 0 :(得分:2)

如果您只对单值感兴趣,这是使用Map<String, Object>的简单解决方案。即使它也可以使用普通POJO类来实现。

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;
    }
}

如果您只对链接感兴趣,请使用JAVA plain POJO类解决方案。

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;
    }
}

答案 1 :(得分:0)

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
   }
}