Stealth Rabbi
Stealth Rabbi

Reputation: 10346

@JsonProperty on class fields - getting duplicate fields in JSON

I have a class Student with some fields. I wanted to give custom names for the JSON fields that get returned.

public class Student {


    @JsonProperty("name")
    private String mName;

    @JsonProperty("DOB")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date mBirthDate;

    @JsonProperty("SSN")
    private String mSocialSecurityNumber;

    public Student() {
    }

    public Student(String mName, Date mBirthDate, String mSocialSecurityNumber) {
        this.mName = mName;
        this.mBirthDate = mBirthDate;
        this.mSocialSecurityNumber = mSocialSecurityNumber;
    }


    public String getName() {
        return mName;
    }

    public void setName(String mName) {
        this.mName = mName;
    }

    public Date getBirthDate() {
        return mBirthDate;
    }

    public void setBirthDate(Date mBirthDate) {
        this.mBirthDate = mBirthDate;
    }

    public String getSocialSecurityNumber() {
        return mSocialSecurityNumber;
    }

    public void setSocialSecurityNumber(String mSocialSecurityNumber) {
        this.mSocialSecurityNumber = mSocialSecurityNumber;
    }
}

My JSON output has both the raw field name (based on the getter name, e.g. getSocialSecurityNumber()), as well as the name specified in my @JsonProperty attributes.

It seems like if I move the @JsonProperty attributes to the getters, then I don't get the doubleup of the fields. Is there not a way I can do this by just having the annotations on the fields, which I feel is a little cleaner?

Upvotes: 1

Views: 6767

Answers (1)

cassiomolin
cassiomolin

Reputation: 130837

Configure the ObjectMapper to consider only the fields:

ObjectMapper mapper = new ObjectMapper();    
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

In Spring Boot you can use Jackson2ObjectMapperBuilder to configure the ObjectMapper:

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {

    return new Jackson2ObjectMapperBuilder() {

        @Override
        public void configure(ObjectMapper objectMapper) {
            super.configure(objectMapper);
            objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
            objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        }
    };
}

Upvotes: 5

Related Questions