2011-07-06 40 views
3

我試圖用傑克遜反序列化最初使用傑克遜創建的一些JSON。該模型具有合成列表獲取器:傑克遜JSON反序列化 - 合成列表獲取器

public List<Team> getTeams() { 
    // create the teams list 
} 

其中該列表不是私人成員,而是在飛行中生成的。現在,這個序列很好,但是在反序列化中使用了getTeams,可能是因爲Jackson看到一個帶有可變列表的getter,並認爲它可以用它作爲setter。 getTeams的內部依賴於傑克遜尚未填充的其他字段。其結果是一個NPE,即我認爲秩序是這裏的問題之一,但不是我想解決的問題之一。

因此,我想要做的是註釋getTeams,以便它永遠不會用作setter,但用作getter。這可能嗎?有什麼建議麼?

回答

4

Disable DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS

mapper.configure(DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS, false); 

使用靜態導入可縮短此行。或者,如果你想要一個註解來爲這個屬性配置一些東西,而不是像上面那樣指定全局設置,那麼將某些東西標記爲「團隊」的設置者。

public class Foo 
{ 
    @JsonSetter("teams") 
    public void asdf(List<Team> teams) 
    { 
    System.out.println("hurray!"); 
    } 

    public List<Team> getTeams() 
    { 
    // generate unmodifiable list, to fail if change attempted 
    return Arrays.asList(new Team()); 
    } 

    public static void main(String[] args) throws Exception 
    { 
    ObjectMapper mapper = new ObjectMapper(); 
    String fooJson = mapper.writeValueAsString(new Foo()); 
    System.out.println(fooJson); 
    // output: {"teams":[{"name":"A"}]} 

    // throws exception, without @JsonSetter("teams") annotation 
    Foo fooCopy = mapper.readValue(fooJson, Foo.class); 
    // output: hurray! 
    } 
} 

class Team 
{ 
    public String name = "A"; 
} 
+0

正確:也注意到,@JsonProperty也將工作,而不是@JsonSetter,因爲它不可能是一個getter由於簽名。 – StaxMan

+0

感謝您的提示。我錯過了這個配置設置,很高興在這個例子中使用它。使用@JsonSetter或@JsonProperty重新路由設置器也很好 – David