Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is @JsonProperty annotation required on accessor methods?

Tags:

java

jackson

I've inherited the following:

import com.fasterxml.jackson.annotation.JsonProperty;
public class MyClass {
  @JsonProperty("id")
  private String id;

  @JsonProperty("id")
  public String getId(){
    ...code...
  }

  @JsonProperty("id")
  public String setId(String id) {
    ...code...
  }
}

Are the repeated JsonProperty annotations required on the getter and setter, or would jackson handle the serialization/deserialization automatically if I only annotated the private member?

like image 854
edwardmlyte Avatar asked Jul 13 '15 10:07

edwardmlyte


People also ask

What is the use of @JsonProperty annotation?

The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.

What is the use of @JsonProperty in Java?

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

Can we use @JsonProperty on class?

But as far as @JsonProperty goes, no, the POJO classes do NOT need anything to mark them as serializable; nor do properties if you have public getter or setter.

What is the use of @JsonIgnoreProperties?

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


2 Answers

In your example, and with default ObjectMapper settings, no annotations should be needed, when using Jackson 1.8 or newer.

Jackson can auto-detect properties from public getters (like "public int getValue()"), setters ("public void setValue(int v);" and fields ("public int value;"). In addition, as long as one public setter, getter or field is found, then matching but (otherwise) non-visible setter/field is also included.

Note, however, that with old Jackson versions (1.7 and earlier) did NOT do second part, and both setter and getter needed to be public.

like image 55
StaxMan Avatar answered Oct 04 '22 23:10

StaxMan


You definitely don't need all those @jsonProperty. Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using. By default it is by getters.

To define the mapper by members:

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.disable(MapperFeature.AUTO_DETECT_GETTERS);

I would recommend anyway also to add this definition:

   mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
like image 38
Uri Shalit Avatar answered Oct 04 '22 23:10

Uri Shalit