The Jackson @JacksonInject annotation can be used to inject the values into parsed objects instead of reading those values from the JSON. In order to inject values into a field, we can use the InjectableValues class and need to configure the ObjectMapper class to read both the injected values from the InjectableValues class and the remaining values from the JSON string.
Syntax
@Target(value={ANNOTATION_TYPE,METHOD,FIELD,PARAMETER}) @Retention(value=RUNTIME) public @interface JacksonInject
Example
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import java.io.*; public class JacksonInjectTest { public static void main(String args[]) throws IOException { String jsonString = "{\"empName\": \"Raja Ramesh\"}"; InjectableValues injectableValues = new InjectableValues.Std().addValue(int.class, 110); Employee emp = new ObjectMapper().reader(injectableValues).forType(Employee.class).readValue(jsonString); System.out.println(emp); } } // Employee class class Employee { @JacksonInject public int empId = 0; public String empName = "Adithya"; @Override public String toString() { return "Employee{" + "empId=" + empId + ", empName='" + empName + '\'' + '}'; } }
Output
Employee{empId=110, empName='Raja Ramesh'}