English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

¿Cuándo usar la anotación @ConstructorProperties en Jackson de Java?

@ConstructorPropertiesComentarios desdejava.beanPaquete pequeño, utilizado para serializar JSON a objetos Java a través de la deserialización Comentarios de construcción. Esta anotación desdeJackson 2.7VersiónComienza a soportar. La forma de funcionamiento de esta anotación es muy simple, en lugar de comentar cada parámetro del constructor, podemos proporcionar el nombre del atributo de cada parámetro del constructor para el array.

Sintaxis

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

Ejemplo

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);
   }
}
//Clase de empleado
class Employee {
   private final int id;
   private final String name; @ConstructorProperties({"id", "name"}) public Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getEmpId() {
      return id;
   }
   public String getEmpName() {
      return name;
   }
}

Resultado de salida

{
 "empName": "Raja",
 "empId": 115
}