Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a property with @JsonIgnore and one with no annotation?

Consider the following class:

private static class Widget {

    @JsonProperty
    private String id = "ID";

    @JsonIgnore
    private String jsonIgnored = "JSON_IGNORED";

    private String noAnnotation = "NO_ANNOTATION";
}

If I serialize this using Jackson, I will end up with this string:

{"id":"ID"}

What is the difference between a property with @JsonIgnore and one with no annotation?

like image 242
mattalxndr Avatar asked Jun 28 '16 13:06

mattalxndr


People also ask

What is the use of @JsonIgnore annotation?

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setters, getters or fields. If you add @JsonIgnore to a field or its getter method, the field is not going to be serialized.

What is the use of @JsonIgnore annotation in spring boot?

@JsonIgnore is used at field level to mark a property or list of properties to be ignored.

What is the difference between JsonIgnore and JsonIgnoreProperties?

@JsonIgnore is to ignore fields used at field level. while, @JsonIgnoreProperties is used at class level, used for ignoring a list of fields. Annotation can be applied both to classes and to properties.

When should I use JsonIgnore?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property.


1 Answers

The @JsonIgnore annotated properties/methods will not be serialized/deserialized by Jackson. While the not annotated will be.

The problem here is that Jackson usually looks for the getters, and you didn't specified any getters. So that's why it's only serialized the @JsonProperty annotated property.

If you implement the 3 getters for the 3 properties, your json will look like this:

{
  "id":"ID",
  "noAnnotation":"NO_ANNOTATION"
}
like image 71
Renato Souza Avatar answered Oct 19 '22 23:10

Renato Souza