2017-02-24 46 views
0

我目前有我的POJO類用於反序列化json源。問題@JsonProperty的方法

public class OpenBuilding extends Building { 

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

凡父類是這樣

public abstract class Buidling { 

    protected String postcode; 

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

我的問題是,字符串郵政編碼是沒有得到映射的。它在字段上使用註釋時有效。但是,由於它是一個繼承的字段,並且我有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