我有一个学生,有一些领域。我想为返回的JSON字段提供自定义名称。
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;
}
}
我的JSON输出包含原始字段名称(基于getter名称,例如getSocialSecurityNumber()),以及我的@JsonProperty
属性中指定的名称。
似乎我将@JsonProperty属性移动到getter,然后我没有获得字段的加倍。有没有办法只通过在田地上注释就可以做到这一点,我觉得它更干净了?
答案 0 :(得分:3)
将ObjectMapper
配置为仅考虑字段:
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
在Spring Boot中,您可以使用Jackson2ObjectMapperBuilder
配置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);
}
};
}