When is the @JsonProperty property used and what is it used for?
The @JsonProperty
annotation is used to specify the property name in a JSON object when serializing or deserializing a Java object using the Jackson library. It is often used when the JSON property name is different from the field name in the Java object, or when the JSON property name is not in camelCase.
For example, suppose you have the following Java object:
public class Person {
private String firstName;
private String lastName;
private int age;
// getters and setters go here
}
If you want to serialize this object to JSON and specify that the JSON property names should be "first_name", "last_name", and "age", you can use the @JsonProperty
annotation like this:
public class Person {
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
@JsonProperty
private int age;
// getters and setters go here
}
Now when you serialize the Person
object to JSON using Jackson, the JSON object will have properties with the names specified in the @JsonProperty
annotations.
Similarly, if you want to deserialize a JSON object to a Person
object and the JSON property names are different from the field names in the Person
class, you can use the @JsonProperty
annotation to specify the correct mapping:
public class Person {
@JsonProperty("first_name")
private String firstName;