【问题标题】:Jackson @JsonIgnore property is nullJackson @JsonIgnore 属性为空
【发布时间】:2014-10-15 06:14:08
【问题描述】:

我想将 json 字符串转换为一个对象。

json 看起来像这样:

{"receive":1413342268310}

对象是这样的:

public class PositionBean {  
    private Long id;
    private Date receive;

    public void setReceive (Date receive) {
        this.receive = receive;
    }

    public void setReceive (Long receive) {
        this.receive = new Date (receive);
    }

    public Long getReceive () {
        return receive.getTime ();
    }
}

我必须在其他类中使用的所有 set 和 get 方法,所以我不能删除一个方法。 当我调用

objectMapper.readValue(str, PositionBean.class);

提示异常,jackon不知道设置了哪个方法,所以我使用@JsonIgnore,但发现receive为null。

【问题讨论】:

  • 您最好的方法可能是编写一个自定义反序列化器,将long 转换为Date。 This question 可能有用。 (我敢肯定有人有这种确切情况的例子;Jackson 甚至可能默认包含这样的映射器。)
  • 你在哪里使用@jsonignore?关于方法?如果是这样,您可以尝试在接收字段中执行此操作吗?
  • 你能更新一下你使用 JSONIgnore 注释的地方吗??

标签: java json jackson


【解决方案1】:

您可以使用注解@JsonSetter 来指定应该使用哪个方法作为setter。

示例:

public class PositionBean {  
    private Long id;
    private Date receive;

    public void setReceive (Date receive) {
        this.receive = receive;
    }

    @JsonSetter
    public void setReceive (Long receive) {
        this.receive = new Date (receive);
    }

    public Long getReceive () {
        return receive.getTime ();
    }
}  

当您用@JsonIgnore 标记setter(例如setXXX)时,这意味着属性XXX 将被忽略。
来自文档:

例如,以其他方式表示属性的“getter”方法 (例如,“getValue”建议属性“value”)进行序列化, 将被忽略并且不会输出此类属性,除非另一个 注释定义了要使用的替代方法。

【讨论】:

    【解决方案2】:

    你也可以使用

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    

    即使您在映射类中没有与 JSON 字段对应的适当字段,这也不会引发任何映射异常。配置完成后,您可以使用您的代码进行进一步处理。

    objectMapper.readValue (str, PositionBean.class);
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2014-10-28
      • 2012-01-01
      • 2018-10-13
      • 2015-12-21
      • 2018-12-31
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      相关资源
      最近更新 更多