java - How to directly write to a JSON object (ObjectNode) from ObjectMapper in Jackson JSON? -
i'm trying output json object in jackson json. however, couldn't json object using following code.
public class myclass { private objectnode jsonobj; public objectnode getjson() { objectmapper mapper = new objectmapper(); // code generate object user... mapper.writevalue(new file("result.json"), user); jsonobj = mapper.createobjectnode(); return jsonobj; } }
after program runs, file result.json
contains correct json data. however, jsonobj
empty (jsonobj={}
). looked javadoc of objectmapper couldn't find easy way write objectnode
(json object in jackson). there no method in objectmapper
following:
public void writevalue(objectnode json, object value)
how write objectnode
directly objectmapper
?
you need make use of objectmapper#valuetotree() instead.
this construct equivalent json tree representation. functionally same if serializing value json , parsing json tree, more efficient.
you don't need write user
object out json file, if that's not required.
public class myclass { private objectnode jsonobj; public objectnode getjson() { objectmapper mapper = new objectmapper(); // code generate object user... jsonnode jsonnode = mapper.valuetotree(user); if (jsonnode.isobject()) { jsonobj = (objectnode) jsonnode; return jsonobj; } return null; } }
Comments
Post a Comment