2015-06-23 33 views
43

我需要更改Java中的JSON屬性值,我可以正確獲取該值,但無法修改JSON。如何修改Java中的JsonNode?

這裏是低於

JsonNode blablas = mapper.readTree(parser).get("blablas"); 
    for (JsonNode jsonNode : blablas) { 
     String elementId = jsonNode.get("element").asText(); 
     String value = jsonNode.get("value").asText(); 
     if (StringUtils.equalsIgnoreCase(elementId, "blabla")) { 
      if(value != null && value.equals("YES")){ 
       // I need to change the node to NO then save it into the JSON 
      } 
     } 
    } 

什麼是做到這一點的最好方法的代碼?

回答

90

JsonNode是不可變的,用於解析操作。但是,它可以轉換成ObjectNode(和ArrayNode),允許突變:

((ObjectNode)jsonNode).put("value", "NO"); 

對於數組,你可以使用:

((ObjectNode)jsonNode).putArray("arrayName").add(object.ge‌​tValue()); 
+0

嘗試了一種數字類型,我需要更改該值。我得到這個異常: '線程中的異常「main」java.lang.ClassCastException:com.fasterxml.jackson.databind.node.IntNode不能轉換爲com.fasterxml.jackson.databind.node.ObjectNode' –

1

您需要獲取ObjectNode類型對象才能設置值。 看看this

0

我想你可以只投給ObjectNode和使用put方法。像這樣

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");