我想知道是否可以快速将一些JSON快速地解释为Java数组,或者是否更好地使用像Jackson这样的东西?
假设我正在解析像这样的JSON对象:
{ "item1": "item",
"roles": [
{ "roleName": "NormalUser" }
],
"type": "worker"
}
然后我在这里有一些Java代码(响应变量=来自RestTemplate的ResponseEntity):
logger.info("parsing role...");
HashMap<String, Object> jsonBody = response.getBody();
if(jsonBody.containsKey("roles")){
@SuppressWarnings("unchecked")
List<HashMap<String, Object>> roles = (List<HashMap<String, Object>>)jsonBody.get("roles");
logger.info("Cast Hashmap, now interpreting...");
for (HashMap<String, Object> role : roles) {
logger.info("Found role: " + role.toString());
String assignedRole = "";
if(role.containsKey("role")){
assignedRole = (String) role.get("roleName");
};
this.roleAssignments.add(assignedRole);
logger.info("Assigning role: {}", assignedRole);
}
}
答案 0 :(得分:1)
您可以尝试JsonPath
例如
String content="some json";
List<String> assignedRoles = JsonPath.read(content, "$.roles[*].roleName");
this.roleAssignments.addAll(assignedRoles);