[英]Parsing JSON using Gson library for JAVA
I am working on parsing a JSON in JAVA which has a structure like this, 我正在使用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"
}
]
}
I need to obtain links.href where rel = "approval_url" 我需要获取links.href,其中rel =“ approval_url”
So far i have been into nested data structure declarations and can not reach to links.href. 到目前为止,我已经进入了嵌套数据结构声明,并且无法访问links.href。 I am using GSON library and here is what my code looks like: 我正在使用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);
This is the simple solution using Map<String, Object>
if you are interested to single value only. 如果只对单个值感兴趣,这是使用Map<String, Object>
的简单解决方案。 Even though it can be achieved using Plain POJO class as well. 即使也可以使用Plain 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;
}
}
Here is the solution with JAVA plain POJO class if you are interested to links only. 如果仅对链接感兴趣,这是JAVA普通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;
}
}
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.