2017-03-02 73 views
0

我在想,如果將某些JSON快速解釋爲Java數組,像這樣或者如果最好使用類似Jackson的東西那麼快?快速解析Java中與數組混合的深json對象

比方說,我解析一個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); 
     } 
    } 
+1

gson或jackson比解析更好 –

+1

實體entity = gson.fromJson(jsonInString,Entity.class); –

回答

1

你可以試試JsonPath

例如

String content="some json"; 
List<String> assignedRoles = JsonPath.read(content, "$.roles[*].roleName"); 
this.roleAssignments.addAll(assignedRoles); 
+0

這是我在Java中看到的用於解析JSON的最好的庫。難以置信... – Dexter