Home > Java > javaTutorial > 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
Release: 2023-08-19 19:09:10
forward
1421 people have browsed it

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
Copy after login

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;;
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template