2016-04-15 96 views
-3

我有一個類,我們說Person,我想使用Jackson填充JSON,但屬性名稱因源而異。這裏的代碼看起來目前:具有不同JSON屬性名稱的繼承模型

class Person { 
    protected String firstName; 
    protected String lastName; 
    protected String address; 

    public abstract void setFirstName(String firstName); 
    public abstract void setLastName(String lastName); 
    public abstract void setAddress(String address); 

    // getters etc. 
} 

class PersonFormat1 extends Person { 
    @Override 
    @JsonProperty("firstName") 
    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    @Override 
    @JsonProperty("lastName") 
    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    @Override("address") 
    public void setAddress(String address) { 
     this.address = address; 
    } 
} 

class PersonFormat2 extends Person { 
    @Override 
    @JsonProperty("fName") 
    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    @Override 
    @JsonProperty("lName") 
    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    @Override("addr") 
    public void setAddress(String address) { 
     this.address = address; 
    } 
} 

正如你所看到的,PersonFormat1PersonFormat2的結構相同,但我以指定不同的屬性名稱需要不同的子類。

有沒有一種方法來強制模型沒有重新聲明和重新實現每種方法的樣板?

回答

1

一種方法是使用PropertyNamingStrategyhttp://wiki.fasterxml.com/PropertyNamingStrategy

這裏是不錯的簡單演示瞭如何你可以用它Link to How to Use PropertyNamingStrategy in Jackson


另一種是使用MixInAnnotations http://wiki.fasterxml.com/JacksonMixInAnnotations

MixInAnnotations你可以創建一個Person類和Mixin的任何其他替代屬性名稱設置。

public static void main(String[] args) throws IOException { 
    ObjectMapper mapper1 = new ObjectMapper(); 
    String person1 = "{\"firstName\":null,\"lastName\":null,\"address\":null}"; 
    Person deserialized1 = mapper1.readValue(person1,Person.class); 

    ObjectMapper mapper2 = new ObjectMapper(); 
    mapper2.addMixIn(Person.class, PersonMixin.class); 
    String person2 = "{\"fName\":null,\"lName\":null,\"addr\":null}"; 
    Person deserialized2 = mapper2.readValue(person2,Person.class); 
} 

public static class Person { 
    @JsonProperty("firstName") 
    String firstName; 
    @JsonProperty("lastName") 
    String lastName; 
    @JsonProperty("address") 
    String address; 

} 

public class PersonMixin { 
    @JsonProperty("fName") 
    String firstName; 
    @JsonProperty("lName") 
    String lastName; 
    @JsonProperty("addr") 
    String address; 
} 
相關問題