2013-08-19 50 views
11

我想輸出到Jackson JSON中的JSON對象。但是,我無法使用以下代碼獲取JSON對象。如何從Jackson JSON中的ObjectMapper直接寫入JSON對象(ObjectNode)?

public class MyClass { 

     private ObjectNode jsonObj; 

     public ObjectNode getJson() { 
       ObjectMapper mapper = new ObjectMapper(); 
       // some code to generate the Object user... 
       mapper.writeValue(new File("result.json"), user); 
       jsonObj = mapper.createObjectNode(); 
       return jsonObj; 
     } 

} 

程序運行後,文件result.json包含正確的JSON數據。但是,jsonObj爲空(jsonObj={})。我擡起頭的ObjectMapper的Javadoc,但無法找到一個簡單的方法來寫一個ObjectNode(傑克遜JSON對象)。有一個在ObjectMapper沒有一種方法如下所示:

public void writeValue(ObjectNode json, Object value) 

如何寫一個ObjectNode直接從ObjectMapper

回答

21

您需要使用ObjectMapper#valueToTree()代替。

這將相當於建造JSON樹表示。功能上與將值序列化爲JSON並將JSON解析爲樹相似,但效率更高。

如果不需要,則不需要將User對象寫出到JSON文件中。

public class MyClass { 

    private ObjectNode jsonObj; 

    public ObjectNode getJson() { 
     ObjectMapper mapper = new ObjectMapper(); 
     // some code to generate the Object user... 
     JsonNode jsonNode = mapper.valueToTree(user); 
     if (jsonNode.isObject()) { 
     jsonObj = (ObjectNode) jsonNode; 
     return jsonObj; 
     } 
     return null; 
    } 
} 
+1

正確的。並且如果輸出到文件是所需的,'JsonNode'可以寫入直接與'writeValue(文件,jsonNode)的文件;' – StaxMan

+0

@Ravi:謝謝。這工作完美。 – tonga

+0

anyidea如何發佈使用傑克遜的書面價值? –