I'm trying to output to a JSON object in Jackson JSON. However, I couldn't get the JSON object using the following code.
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 ObjectMapper but couldn't find an easy way to write to a ObjectNode
(JSON object in Jackson). There is no method in ObjectMapper
like the following:
public void writeValue(ObjectNode json, Object value)
How to write to an ObjectNode
directly from ObjectMapper
?
You need to make use of ObjectMapper#valueToTree() instead.
This will construct equivalent JSON Tree representation. Functionally same as if serializing value into JSON and parsing JSON as tree, but more efficient.
You don't need to write the User
object out to a JSON file, if that's not required.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.