Home > Java > javaTutorial > When to use @ConstructorProperties annotation when using Jackson in Java?

When to use @ConstructorProperties annotation when using Jackson in Java?

PHPz
Release: 2023-08-27 20:53:05
forward
1148 people have browsed it

When to use @ConstructorProperties annotation when using Jackson in Java?

@ConstructorProperties The annotation comes from the java.bean package and is used to convert JSON through the annotated constructor. Serialized to java object. This annotation is supported starting with Jackson 2.7 version. The way this annotation works is very simple, instead of annotating each parameter in the constructor, we can provide an array containing the property names for each constructor parameter.

Syntax

@Documented
@Target(value=CONSTRUCTOR)
@Retention(value=RUNTIME)
public @interface ConstructorProperties
Copy after login

Example

import com.fasterxml.jackson.databind.ObjectMapper;
import java.beans.ConstructorProperties;
public class ConstructorPropertiesAnnotationTest {
   public static void main(String args[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      Employee emp = new Employee(115, "Raja");
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// Employee class
class Employee {
   private final int id;
   private final String name;
<strong>   </strong>@ConstructorProperties({"id", "name"})<strong>
</strong>   public Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getEmpId() {
      return id;
   }
   public String getEmpName() {
      return name;
   }
}
Copy after login

Output

{
 "empName" : "Raja",
 "empId" : 115
}
Copy after login

The above is the detailed content of When to use @ConstructorProperties annotation when using Jackson in Java?. 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