Add Additional Fields with @JacksonInject

@JacksonInject annotation is particularly valuable when you need to supply contextual data or configuration settings that are not present in the JSON being deserialized.

To utilize the@JacksonInject annotation, follow these steps:

  • Create a field in your class and annotate it with @JacksonInject.
  • The field’s type should match the type of the value you want to inject.
  • During deserialization, Jackson will look for a matching value based on the field’s type and name.

Here’s an example:

public class Person {
    private Long id;
    private String name;
    private Long processTimeInMills;

    // Getters and setters (not shown for brevity)

In the above example, the processTimeInMills field is annotated with @JacksonInject. During deserialization, Jackson will look for a value of type String with the name processTimeInMills and inject it into the Person object.

        String json = "{\"id\": 1, \"name\": \"Alice\"}";

        InjectableValues.Std injectableValues = new InjectableValues.Std()
                .addValue("processTimeInMills", System.currentTimeMillis());

        ObjectMapper objectMapper = new ObjectMapper();

        Person person = objectMapper.readValue(json, Person.class);

        System.out.println("Person ID: " + person.getId());
        System.out.println("Person Name: " + person.getName());
        System.out.println("Process Time: " + person.getProcessTimeInMills());


Person ID: 1
Person Name: Alice
Process Time: 1698322949038

Changing Field Names for Deserialization

@JsonProperty annotation also works for deserialization.

private static void deserialize() throws JsonProcessingException {
        String json = "{\"id\":1,\"full_name\":\"Alice\",\"birth_date\":\"1990-05-15\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);

        System.out.println("JSON String to Person object: " + person);

Tht output:

JSON String to Person object: Person(id=1, name=Alice, dateOfBirth=1990-05-15)

Read More