ton*_*nga 12 java json jackson
我正在尝试输出Jackson 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;
}
}
Run Code Online (Sandbox Code Playgroud)
程序运行后,该文件result.json
包含正确的JSON数据.但是,jsonObj
是空的(jsonObj={}
).我查找了ObjectMapper的Javadoc,但找不到一种简单的方法来写入ObjectNode
(Jackson中的JSON对象).没有ObjectMapper
像下面这样的方法:
public void writeValue(ObjectNode json, Object value)
Run Code Online (Sandbox Code Playgroud)
如何ObjectNode
直接写入ObjectMapper
?
Rav*_*yal 22
您需要使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20990 次 |
最近记录: |