Java 如何从Jackson JSON中的ObjectMapper直接写入JSON对象(ObjectNode)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18320419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to directly write to a JSON object (ObjectNode) from ObjectMapper in Hymanson JSON?
提问by tonga
I'm trying to output to a JSON object in Hymanson JSON. However, I couldn't get the JSON object using the following code.
我正在尝试输出到 Hymanson JSON 中的 JSON 对象。但是,我无法使用以下代码获取 JSON 对象。
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;
}
}
After the program runs, the file result.json
contains the correct JSON data. However, jsonObj
is empty (jsonObj={}
). I looked up the Javadoc of ObjectMapperbut couldn't find an easy way to write to a ObjectNode
(JSON object in Hymanson). There is no method in ObjectMapper
like the following:
程序运行后,该文件result.json
包含正确的 JSON 数据。然而,jsonObj
是空的(jsonObj={}
)。我查找了ObjectMapper的 Javadoc,但找不到一种简单的方法来写入ObjectNode
(Hymanson 中的 JSON 对象)。没有ObjectMapper
像下面这样的方法:
public void writeValue(ObjectNode json, Object value)
How to write to an ObjectNode
directly from ObjectMapper
?
如何ObjectNode
直接从写入ObjectMapper
?
采纳答案by Ravi Thapliyal
You need to make use of ObjectMapper#valueToTree()instead.
您需要改用ObjectMapper#valueToTree()。
This will construct equivalent JSON Tree representation. Functionally same as if serializing value into JSON and parsing JSON as tree, but more efficient.
这将构造等效的 JSON 树表示。在功能上与将值序列化为 JSON 并将 JSON 解析为树一样,但效率更高。
You don't need to write the User
object out to a JSON file, if that's not required.
如果不需要,则无需将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;
}
}