2017-01-28 43 views
0

私はいくつかのフィールドを持つクラスの学生がいます。返されるJSONフィールドのカスタム名を付けたいと思っていました。クラスフィールドの@JsonProperty - 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出力は、(ゲッター名に基づいて、例えばgetSocialSecurityNumber())生のフィールド名の両方を持っているだけでなく、私の@JsonProperty属性で指定した名前。

@JsonProperty属性をgetterに移動すると、そのフィールドの倍数が取得されないようです。私は少しだけクリーナーであると感じる分野で注釈を付けるだけで、私がこれを行うことができる方法はありませんか?

答えて

2

設定フィールドのみを考慮するObjectMapper:春ブーツで

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

あなたがObjectMapperを設定するために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); 
     } 
    }; 
} 
+0

ない - それを使用していません。これは、Springブート1.4.3を介して私のためにフードの下で起こっています。 –

+0

@StealthRabbiしたがって、 'Jackson2ObjectMapperBuilder'を使用することができます。私に例を教えてください。 –

+0

ここに示すようにBeanを操作できるようです: http://stackoverflow.com/questions/28324352/how-to-customise-the-jackson-json-mapper-implicitly-used-by-spring-boot –

関連する問題