@JacksonInject annotation is used to indicate that value of annotated property will be injected during deserialization. This is useful if we want to add additional information which is not included in the source JSON.
Example
package com.logicbig.example;
import com.fasterxml.jackson.annotation.JacksonInject;
import java.time.LocalDateTime;
public class CurrencyRate {
private String pair;
private double rate;
@JacksonInject("lastUpdated")
private LocalDateTime lastUpdated;
.............
}
package com.logicbig.example;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.time.LocalDateTime;
public class ExampleMain {
public static void main(String[] args) throws IOException {
String s = "{\"pair\":\"USD/JPY\",\"rate\":109.15}";
System.out.println("JSON input: " + s);
InjectableValues iv = new InjectableValues.Std();
((InjectableValues.Std) iv).addValue("lastUpdated", LocalDateTime.now());
ObjectMapper om = new ObjectMapper();
om.setInjectableValues(iv);
CurrencyRate cr = om.readValue(s, CurrencyRate.class);
System.out.println(cr);
}
}
JSON input: {"pair":"USD/JPY","rate":109.15} CurrencyRate{pair='USD/JPY', rate=109.15, lastUpdated=2018-06-01T14:54:45.895580900}
Injecting by type
In above example we injected 'lastUpdated' field by an id (via @JacksonInject#value). What if we don't specify the value i.e.
@JacksonInject
private LocalDateTime lastUpdated;
In that case the property will be injected by type and we have to use another overloaded method of InjectableValues.Std#addValue() which specifies the target property type instead of the id:
...
InjectableValues iv = new InjectableValues.Std();
((InjectableValues.Std) iv).addValue(LocalDateTime.class, LocalDateTime.now());
...
Example ProjectDependencies and Technologies Used: - jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
- JDK 10
- Maven 3.3.9
|