使用 @JsonIgnore 注解和不使用注解的属性有什么区别?

8

Consider the following class:

private static class Widget {

    @JsonProperty
    private String id = "ID";

    @JsonIgnore
    private String jsonIgnored = "JSON_IGNORED";

    private String noAnnotation = "NO_ANNOTATION";
}

如果我使用Jackson进行序列化,最终会得到以下字符串:
{"id":"ID"}

一个带有 @JsonIgnore 注解的属性和一个没有注解的属性之间有什么区别?
1个回答

8

@JsonIgnore注释的属性/方法将不会被Jackson序列化/反序列化。而未注释的属性/方法会被序列化/反序列化。

问题在于Jackson通常寻找getter方法,而你没有指定任何getter方法。这就是为什么只序列化了@JsonProperty注释的属性。

如果你实现3个属性的3个getter方法,你的JSON将如下所示:

{
  "id":"ID",
  "noAnnotation":"NO_ANNOTATION"
}

那么,没有注释的字段和带有@JsonProperty注释的字段之间有什么区别呢? - Frax
2
当没有 @JsonProperty 注释时,生成的输出将基于属性名称。 假设您的属性名为 textDescription,但您需要它为 "text-description"。 那么您应该使用 @JsonProperty("text-description")。 - Renato Souza

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