JsonProperty
- Java course
- Intermediate
- Lesson 79/116
- 5 min
Learn field mapping with @JsonProperty.
Field names with @JsonProperty
When the text key must differ from the Java field name, use the @JsonProperty annotation. For example, @JsonProperty("user_name") String userName serializes as user_name in the structured text. This is useful when Java uses camelCase but the text uses snake_case.
For records, the annotation goes on the constructor parameter: record User(@JsonProperty("user_name") String userName, int age) {}. Jackson applies the same name in both serialization and parsing, so one class fits multiple text formats.
Record vs POJO
Records carry immutable data; they have no setters. POJOs offer mutable fields with getter/setter pairs. Jackson supports both; records are shorter and safer.
In a POJO, Jackson derives keys from getter names: getUserName() becomes the key userName. In records, the field name is used directly. Modern code prefers records.
Practice Define User with @JsonProperty
Define record User(@JsonProperty("user_name") String userName, @JsonProperty("user_age") int userAge) {}. Add throws Exception to main. Create an ObjectMapper mapper = new ObjectMapper();, build a user with User u = new User("Ayşe", 30);, produce text with String text = mapper.writeValueAsString(u); and print System.out.println(text);.
Starter code
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
// User record with @JsonProperty for user_name and user_age
public class Main {
public static void main(String[] args) throws Exception {
// ObjectMapper, User instance, writeValueAsString and println
}
}Sample solution
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
record User(@JsonProperty("user_name") String userName, @JsonProperty("user_age") int userAge) {}
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
User u = new User("Ayşe", 30);
String text = mapper.writeValueAsString(u);
System.out.println(text);
}
}Expected output
{"user_name":"Ayşe","user_age":30}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the @JsonProperty usages
| Term | Meaning |
|---|---|
@JsonProperty("user_name") |
Customizes the key |
camelCase |
Java field naming convention |
snake_case |
Text key naming convention |
record parameter |
Annotation location |
2 What does @JsonProperty("user_name") do?
- Sets the text key name to user_name Correct answer
- Hides the field
- Makes the field final
- Makes the field static
Explanation: @JsonProperty sets the text key name.
3 Complete the @JsonProperty usage
record User(@____("user_name") String userName, int age) {}
record User(@JsonProperty("user_name") String userName, int age) {}
Explanation: The @JsonProperty annotation goes on the record parameter.