@JacksonInject annotation specifies that the value of annotated property will be injected during deserialization. We can use this feature, if we want to add additional information which is not included in the input/source JSON.
Find the below working application.
Employee4.java
package com.sample.app.model;
import java.util.Date;
import com.fasterxml.jackson.annotation.JacksonInject;
public class Employee4 {
private int id;
private String name;
@JacksonInject("createdTime")
private Date createdDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Override
public String toString() {
return "Employee4 [id=" + id + ", name=" + name + ", createdDate=" + createdDate + "]";
}
}
JacksonInjectDemo.java
package com.sample.app;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee4;
public class JacksonInjectDemo {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String inputJson = "{\"id\":1,\"name\":\"Krishna\"}";
System.out.println("JSON input: " + inputJson);
InjectableValues injectableValues = new InjectableValues.Std();
((InjectableValues.Std) injectableValues).addValue("createdTime", new Date());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setInjectableValues(injectableValues);
Employee4 emp4 = objectMapper.readValue(inputJson, Employee4.class);
System.out.println(emp4);
}
}
Output
JSON input: {"id":1,"name":"Krishna"} Employee4 [id=1, name=Krishna, createdDate=Fri May 19 11:27:59 IST 2023]
No comments:
Post a Comment