我正在尝试使用Jackson对最初使用Jackson创建的一些JSON进行反序列化。该模型有一个合成列表getter:
public List<Team> getTeams() {
// create the teams list
}
其中列表不是私有成员,而是动态生成的。现在这个串行很好,但在反序列化中使用getTeams,大概是因为Jackson看到一个带有可变列表的getter并且认为它可以将它用作setter。 getTeams的内部依赖于杰克逊尚未填充的其他领域。其结果是NPE,即我认为顺序是这里的问题之一,但不是我想要解决的问题。
所以,我想要做的是注释getTeams,以便它从未用作setter但 用作getter。这可能吗?有什么建议吗?
答案 0 :(得分:4)
禁用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";
}