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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With