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

何时在Java的Jackson中使用@ConstructorProperties批注?

@ConstructorPropertiesCommentaire provenant dejava.beanPetit colis, utilisé pour sérialiser JSON en objet Java Commentaire de construction。Ce commentaire vient deJackson 2.7VersionCette version prend en charge. Le mode de fonctionnement de ce commentaire est très simple, au lieu de commenter chaque paramètre du constructeur, nous pouvons fournir le nom de l'attribut de chaque paramètre du constructeur pour l'array.

Grammaire

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

Exemple

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);
   }
}
//Classe d'employé
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;
   }
}

Résultat de la sortie

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