Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roamingthings/99b2a139c24de073ffdbed3763a9bd08 to your computer and use it in GitHub Desktop.
Save roamingthings/99b2a139c24de073ffdbed3763a9bd08 to your computer and use it in GitHub Desktop.
Code snippets to use a Jackson 2 `ObjectMapper` and `JsonNode` to generate JSON documents.
ObjectMapper objectMapper = new ObjectMapper()
// Find and register modules e.g. for serialization or JAXB annotation processing
.findAndRegisterModules()
// Order map entries by key
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
// Don't fail on empty beans
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
// Write date values as timestamp instead of ms since epoch
.enable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)
// Don't include default view / non @JsonView annotaded values
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
// Only include non empty values
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// Set @JsonView for the mapper
objectMapper.setConfig(
objectMapper.getSerializationConfig()
.withView(Views.MyView.class));
// Customize Use if you want to customize the date format
SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
objectMapper.setDateFormat(dateformat);
// Create the node factory that gives us nodes.
JsonNodeFactory factory = new JsonNodeFactory(false);
// create a json factory to write the treenode as json. for the example
// we just write to console
JsonFactory jsonFactory = new JsonFactory();
// Generate to `outputStream`
OutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator generator = jsonFactory.createGenerator(outputStream);
// Set the ObjectMapper to encode/decode POJOs
generator.setCodec(objectMapper);
// the root node
final ObjectNode myRootNode = factory.objectNode();
// ...
// Serialize a POJO using the mapper and add a custom node
final ObjectNode node = objectMapper.valueToTree(myPOJO);
node.putString("my-custom-property", "Duke")
myRootNode.set("my-pojo", node);
// Finally generate the JSON document
objectMapper.writeValue(generator, siteDefinitionNode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment