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.
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.
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
}When @JsonProperty is used without a value (as on the age field), Jackson defaults to using the exact field name. 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;
@JsonProperty("last_name")
private String lastName;
@JsonProperty
private int age;
// getters and setters go here
}Here is a practical example using ObjectMapper to demonstrate both serialization and deserialization:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Serialization
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
person.setAge(30);
String json = mapper.writeValueAsString(person);
System.out.println(json);
// Output: {"first_name":"John","last_name":"Doe","age":30}
// Deserialization
String inputJson = "{\"first_name\":\"Jane\",\"last_name\":\"Smith\",\"age\":25}";
Person deserializedPerson = mapper.readValue(inputJson, Person.class);
System.out.println(deserializedPerson.getFirstName());
// Output: Jane
}
}Note: Jackson provides default naming strategies (like
SNAKE_CASE) that can automatically convert camelCase field names to other formats without needing@JsonPropertyon every field. You can enable these globally usingmapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).