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?
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.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
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.
@JsonIgnoreProperties is used at class level to mark a property or list of properties to be ignored.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With