【问题标题】:Jackson JSON deserialization - synthetic list getterJackson JSON 反序列化 - 合成列表获取器
【发布时间】:2011-07-06 16:42:10
【问题描述】:

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

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

列表不是私有成员,而是动态生成的。现在这个序列化很好,但在反序列化中使用 getTeams,大概是因为杰克逊看到一个带有可变列表的 getter 并认为它可以将它用作 setter。 getTeams 的内部依赖于 Jackson 尚未填充的其他字段。结果是 NPE,即我认为订单是这里的问题之一,但不是我想要解决的问题。

所以,我想做的是对 getTeams 进行注释,这样它就不会被用作 setter,而是 被用作 getter。这可能吗?有什么建议吗?

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

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

    【讨论】:

    • 正确:还要注意@JsonProperty 也可以代替@JsonSetter 工作,因为由于签名它不能是getter。
    • 感谢您的提示。我错过了那个配置设置,很高兴在这种情况下使用它。也很高兴了解使用 @JsonSetter 或 @JsonProperty 重新路由设置器
    猜你喜欢
    • 2023-03-04
    • 2011-04-12
    • 1970-01-01
    • 2023-03-13
    • 2015-02-28
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多