@JsonProperty Annotation - Jackson Tutorial



@JsonProperty Annotation is a Marker Annotation of Jackson API.

@JsonProperty Annotation can be used for two purposes:

1.  @JsonProperty annotation that can be used to define a non-static object field to be used (serialized, deserialized) as a logical property.

@JsonProperty(name), tells Jackson ObjectMapper to map the JSON property name to the annotated Java field’s name.

//example of json that is submitted {  "Type":"Ferrari",}//where it gets mapped public static class Car {  @JsonProperty("Type")  public String type; }

Mainly, it is used to rename the variable when JSON field name is different than JAVA member variable.

public class Parameter {  @JsonProperty("Name") . // JSON has Name but JAVA has name  public String name;  @JsonProperty("Value")  public String value; }

This correctly parses to/from the JSON:

"Parameter":{  "Name":"Parameter-Name",  "Value":"Parameter-Value"}

2. @JsonProperty Annotation that can be used to define a non-static method as a “setter” or “getter” for a logical property (depending on its signature)

JsonProperty is ALSO used to specify getter and setter methods for the variable apart from usual serialization and deserialization. For example,

public class Student {    public int id;    private String name;    @JsonProperty("name")    public void setTheName(String name) {        this.name = name;    }    @JsonProperty("name")    public String getTheName() {        return name;    }}

If you have to rename the variable in serialization/deserialization. @JsonProperty is a metadata to tell serializer how to serial object. It is used to:

1. variable name2. access (READ, WRITE)3. default value4. required/optional

For example:

public class Parameter {  @JsonProperty(        value="Name",        required=true,        defaultValue="No name",        access= Access.READ_WRITE)  public String _name;  @JsonProperty(        value="Value",        required=true,        defaultValue="Empty",        access= Access.READ_WRITE)  public String _value; }

References:

  1. http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html#required()
  2. https://stackoverflow.com/questions/12583638/when-is-the-jsonproperty-property-used-and-what-is-it-used-for
  3. https://stackoverflow.com/questions/11526874/jsonproperty-annotation-on-field-as-well-as-getter-setter
  4. https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations