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
1272 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:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template