Home > front end >  Java and @JsonProperty
Java and @JsonProperty

Time:03-31

I am wondering if there is a way to apply @JsonProperty to an inherited fields of a class. For example I have the following classes.

public class Person {
    protected String id;
    protected String firstName;
    protected String middleName;
    protected String lastName;
}

...

/**
 * need to figure out here, how to apply @JsonProperty
 * to the fields below of the parent class:
 * protected String id;
 * protected String firstName;
 * protected String middleName;
 * protected String lastName;
 */
public class Employee extends Person {
   @JsonProperty("DepartmentID")
   protected String departmentId;
}

the goal here is that only Employee class will have @JsonProperty not the Person class.

Thanks.

CodePudding user response:

Override getter methods with @JsonProperty

   @JsonProperty("DepartmentID")
   protected String departmentId;
   @Override
   @JsonProperty("id")
   public String getId(){
     return super.getId();
   }
 // other getter methods
}

CodePudding user response:

Use getters and setters and annotate your getter instead of the field. Jackson will automatically detect the setter based on the getter name.

public class Person {
    private String id;
    private String firstName;
    private String middleName;
    private String lastName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

   .. etc ...
}

public class Employee extends Person {
    @JsonProperty("id")
    @Override
    public String getId() {
        return super.getId();
    }

    ... etc ...
}
  • Related