杰克逊JSON反序列化-合成列表getter

4

我正在尝试使用Jackson来反序列化一些最初使用Jackson创建的JSON。该模型具有合成列表getter:

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

在这种情况下,列表不是私有成员,而是在运行时生成。现在这个序列化很好,但在反序列化中使用getTeams,可能是因为Jackson看到了一个具有可变列表的getter,并认为它可以用作setter。getTeams的内部依赖于其他字段,Jackson尚未填充。结果是NPE,即我认为顺序是问题之一,但不是我想解决的问题。
所以,我想注释getTeams,使其永远不被用作setter,但是被用作getter。这可能吗?有什么建议吗?
1个回答

5

禁用DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS

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

使用静态导入可使此行更短。

或者,如果您想要一个注释仅为此属性配置事物,并且不像上面那样指定全局设置,则将某些内容标记为“teams”的setter。

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";
}

请注意,@JsonProperty也可以代替@JsonSetter使用,因为由于签名问题,它不能作为getter。 - StaxMan
感谢提供的建议。我之前忽略了这个配置设置,很高兴在这种情况下能够使用它。还很好知道可以使用 @JsonSetter 或 @JsonProperty 重新路由 setter 方法。 - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接