【问题标题】:what is the real use of the annotation @JsonIgnore注释@JsonIgnore的真正用途是什么
【发布时间】:2020-02-02 07:53:58
【问题描述】:

我正在加入具有一对多基数的表,我正在使用的类相互引用。而且我正在使用@JsonIgnore 注释而没有深入理解它。

【问题讨论】:

标签: java json hibernate spring-boot


【解决方案1】:

@JsonIgnore 用于忽略序列化反序列化中使用的逻辑属性。 @JsonIgnore 可用于 settersgettersfields

如果将@JsonIgnore 添加到字段或其getter 方法中,则该字段不会被序列化。

示例 POJO:

class User {
    @JsonIgnore
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    @JsonIgnore
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

序列化示例代码:

ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setId(2);
user.setName("Bob");
System.out.println(mapper.writeValueAsString(user));

控制台输出:

{"name":"鲍勃"}

【讨论】:

  • 如果我将 @JsonIgnore 属性放在 fetch 类型的惰性集合上,这是否意味着不会加载惰性数据?
【解决方案2】:

将你的对象序列化为 Json 时,带有@JsonIgnore 标记的字段将不会包含在序列化的 Json 对象中。此属性由 Json 序列化使用反射读取。

【讨论】:

    【解决方案3】:

    Jackson 的@JsonIgnore 注释可以放在字段上,getter/setess 和构造函数参数标记在序列化为 JSON(或从 JSON 反序列化)期间要忽略的属性。详情请参阅Jackson annotations reference documentation

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2020-08-07
      • 2013-06-01
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多