Custom JSON Deserialization with Jackson

suggest change

A REST API often returns JSON that is mapped to a POJO. Jackson 2's com.fasterxml.jackson.databind.ObjectMapper works out of the box in most cases. Sometimes a custom deserializer is required. This page shows how to write one. The Jackson 1 package org.codehaus.jackson is a different library.

Let’s say we have following entities.

public class User {
    private Long id;
    private String name;
    private String email;

    // getters and setters omitted; the default ObjectMapper does not see private fields
}

And

public class Program {
    private Long id;
    private String name;
    private User createdBy;
    private String contents;

    // getters and setters omitted; the default ObjectMapper does not see private fields
}

Let’s serialize/marshal an object first.

User user = new User();
user.setId(1L);
user.setEmail("example@example.com");
user.setName("Bazlur Rahman");

Program program = new Program();
program.setId(1L);
program.setName("Program @# 1");
program.setCreatedBy(user);
program.setContents("Some contents");

ObjectMapper objectMapper = new ObjectMapper();
final String json = objectMapper.writeValueAsString(program);
System.out.println(json);

writeValueAsString throws checked JsonProcessingException. With the omitted getters, the code produces this JSON:

{
    "id": 1,
    "name": "Program @# 1",
    "createdBy": {
        "id": 1,
        "name": "Bazlur Rahman",
        "email": "example@example.com"
    },
    "contents": "Some contents"
}

The reverse, readValue, maps that JSON back to a Program.

An API may instead return JSON that does not match Program:

{
  "id": 1,
  "name": "Program @# 1",
  "ownerId": 1,
  "contents": "Some contents"
}

ownerId is not a property of Program. Deserializing this JSON with the default mapper throws an unrecognized-property exception.

Two ways to accept it:

Ignore the unknown fields

Ignore ownerId with this annotation on Program:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Program {
    // existing fields stay
}

Write custom deserializer

When ownerId is the id of a User, a custom deserializer can build that User.

Read a JsonNode from the JsonParser, then read each field with get. The name must match exactly; a mismatch yields null and then a NullPointerException on asLong() or asText().

public class ProgramDeserializer extends JsonDeserializer<Program> {
    @Override
    public Program deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        JsonNode node = parser.getCodec().readTree(parser);
        User createdBy = new User();
        createdBy.setId(node.get("ownerId").asLong());

        Program program = new Program();
        program.setId(node.get("id").asLong());
        program.setName(node.get("name").asText());
        program.setCreatedBy(createdBy);
        program.setContents(node.get("contents").asText());
        return program;
    }
}

Register ProgramDeserializer on the ObjectMapper. readValue throws checked IOException.

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Program.class, new ProgramDeserializer());
 
mapper.registerModule(module);
 
String newJsonString = "{\"id\":1,\"name\":\"Program @# 1\",\"ownerId\":1,\"contents\":\"Some contents\"}";
final Program program2 = mapper.readValue(newJsonString, Program.class);

Alternatively, register the deserializer on the class:

@JsonDeserialize(using = ProgramDeserializer.class)
public class Program {
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents