Taco Steemers

A personal blog.

Notes on manually using Jackson (java)

Jackson can be used to do JSON and XML serialization and deserialization in Java. These notes are on how to use Jackson manually.

Jackson can be used to do JSON and XML serialization and deserialization in Java. These notes are on how to use Jackson manually. Baeldung has a good page as well .

Deserializing a single object

ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(exampleString);
return mapper.convertValue(rootNode, Example.class);

Deserializing an embedded single object

ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(exampleString);
JsonNode exampleNode = rootNode.get("example");
return mapper.convertValue(exampleNode, Example.class);

Deserializing a list of objects of the same type

ObjectMapper objectMapper = new ObjectMapper();
List<Example> exampleList = mapper.readValue(requestBody, new TypeReference<List<Example>>() {});

Checking whether a node is null

A node will be null if it was never set. It will be a NullNode if it was removed.

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = mapper.readTree(exampleString);
    JsonNode exampleNode = rootNode.get("example");
    if (null == exampleNode || exampleNode instanceof NullNode) {
        // The node should be considered null.
    }