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

Quando utilizzare l'annotazione @ConstructorProperties in Jackson di Java?

@ConstructorPropertiescommenti sono statijava.beanimballaggio piccolo, utilizzato per deserializzare JSON in oggetti Java costruire commenti. Questo commento è statoVersione 2.7 di JacksonQuesta versione supporta la funzionalità di commento molto semplicemente, piuttosto che commentare ogni parametro del costruttore, possiamo fornire il nome dell'attributo per ogni parametro del costruttore dell'array.

Sintassi

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

Esempio

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);
   {}
{}
//Casta degli impiegati
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;
   {}
{}

Risultato di output

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