2017-02-24 2 views
0

私は現在、jsonソースをデシリアライズするための私のPOJOクラスを持っています。親クラスは、私の問題は、文字列の郵便番号がまったくマッピングされて取得されていないということです Issue @JsonProperty onメソッド

public abstract class Buidling { 

    protected String postcode; 

    public String getPostcode() { 
     return this.postcode; 
    } 
} 

ようです

public class OpenBuilding extends Building { 

    @JsonProperty("BuildingPostCode") 
    @Override 
    public String getPostcode() { 
     return super.getPostcode(); 
    } 
} 

。フィールド上の注釈を使用するときに機能します。しかし、それは継承されたフィールドであり、同じデータに対して異なるプロパティ名を使用するBuildingの他の子を持っているので、それをそのように実装することはできません。

例えば

public class DirectedBuilding extends Building { 

    @JsonProperty("Pseudo_PostCode") 
    @Override 
    public String getPostcode() { 
     return super.getPostcode(); 
    } 
} 

答えて

0

おそらく@JsonCreatorでコンストラクタを定義してみてください。

class Parent { 

    private final String foo; 

    public Parent(final String foo) { 
     this.foo = foo; 
    } 

    public String getFoo() { 
     return foo; 
    } 
} 

class Child extends Parent { 

    @JsonCreator 
    public Child(@JsonProperty("foo") final String foo) { 
     super(foo); 
    } 

    @JsonProperty("foo") 
    public String getFoo() { 
     return super.getFoo(); 
    } 
} 


public static void main(String[] args) throws Exception { 
    final ObjectMapper objectMapper = new ObjectMapper(); 
    final Child toSerialize = new Child("fooValue"); 

    // Serialize the object to JSON 
    final String json = objectMapper.writer() 
      .withDefaultPrettyPrinter() 
      .writeValueAsString(toSerialize); 

    // Prints { "foo" : "fooValue" } 
    System.out.println(json); 

    // Deserialize the JSON 
    final Child deserializedChild = objectMapper.readValue(json, Child.class); 

    // Prints fooValue 
    System.out.println(deserializedChild.getFoo()); 
} 
+0

このケースでは便利ですが、他のいくつかのクラスでは10-20個の変数に対してこれを行う必要がある場合には保守性が低下します – Flemingjp