Jackson Tips: ObjectNode.putPOJO(), putRawValue() for fun and profit

aka “No Need to Convert from Map to JsonNode”

Jackson works with All Kinds of Java Types

Tree Model for Reading content

{ "id" : 123,
"name" : "Bob",
"properties" : {
"value" : 15.0
ObjectMapper mapper = new JsonMapper();
JsonNode root = mapper.readTree(jsonContent);
double value = root.at("/properties/value").asDouble();
// assuming MyValue has compatible structure
MyValue value = mapper.treeToValue(root, MyValue.class);
// converting to Map fine as well:
Map<String, Object> map = mapper.treeToValue(root, Map.class);

Tree Model for generating content

ObjectNode obToWrite = mapper.createObjectNode();
obToWrite.put("id", 123);
obToWrite.put("name", "Bob");
// and so on... and then serialize
OutputStream out = ...;
mapper.writeValue(out, obToWrite);
ObjectNode obToWrite = mapper.createObjectNode();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof Integer) {
obToWrite.put(key, ((Integer) value).intValue();
} else {
// and so on for all content types

No-Conversion Tree Model usage: just add “POJO”s!

String json = mapper.writeValueAsString(map);
ObjectNode root = mapper.createObjectNode();
root.put("id", id);
Map<String, Object> props = createValueMap();
root.putPOJO("properties", props);
Person p = fetchPersonalInformation(in);
root.putPOJO("personal", p);
String json = mapper.writeValueAsString();
static class PojoWithNode {
public int id;
public JsonNode extraData;
PojoWithNode pwn = ...;
String json = mapper.writeValueAsString(pwn);

Pre-serialized Content Inclusion with Tree Model

MyStuff reusableContent = ...;
RawValue raw =
new RawValue(mapper.writeValueAsString(reusableContent));
// ...
ObjectNode root = mapper.createObjectNode();
root.put("id", 358);
// and other stuff
// and then something that has already been serialized (or
// possibly received from somewhere and not deserialized at all)
root.putRawValue("other", raw);

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox