Java
JsonProperty
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.
Exercise 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);.
Show example 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);
}
}
Test yourself
-
Match the @JsonProperty usages
- @JsonProperty("user_name")
- Customizes the key
- camelCase
- Java field naming convention
- snake_case
- Text key naming convention
- record parameter
- Annotation location
-
What does @JsonProperty("user_name") do?
- Sets the text key name to user_name
- Hides the field
- Makes the field final
- Makes the field static
Show answer
Sets the text key name to user_name — @JsonProperty sets the text key name.
-
Complete the @JsonProperty usage
record User(@____("user_name") String userName, int age) {}
Show answer
record User(@JsonProperty("user_name") String userName, int age) {}
Next lesson: List and Map serialization