Home  >  Article  >  Java  >  In Java, what is the purpose of the @JacksonInject annotation when using the Jackson library?

In Java, what is the purpose of the @JacksonInject annotation when using the Jackson library?

WBOY
WBOYforward
2023-08-19 19:09:101384browse

In Java, what is the purpose of the @JacksonInject annotation when using the Jackson library?

Jackson's @JacksonInject annotation can be used to inject a value into the parsed object instead of reading it from JSON Take these values. In order to inject values ​​into fields, we can use the InjectableValues class and need to configure the ObjectMapper class to read the injected values ​​from the InjectableValues ​​ class and from the JSON Read the remaining values ​​from the 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<strong> </strong>injectableValues = new InjectableValues.Std().addValue(int.class, 110);
      Employee emp = new  ObjectMapper().reader(injectableValues).forType(Employee.class).readValue<strong>(</strong>jsonString);
      System.out.println(emp);
   }
}
// Employee class
class Employee {
<strong>   </strong>@JacksonInject<strong>
</strong>   public int empId = 0;
   public String empName = "Adithya";
<strong>   </strong>@Override
   public String toString() {
      return "Employee{" +
      "empId=" + empId +
      ", empName=&#39;" + empName + &#39;\&#39;&#39; +
      &#39;}&#39;;
   }
}

Output

Employee{empId=110, empName=&#39;Raja Ramesh&#39;}

The above is the detailed content of In Java, what is the purpose of the @JacksonInject annotation when using the Jackson library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete