Renaming and ignoring fields with annotations
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A partner wants full_name, a response must never contain a password hash, and a courier wants dates as 22-09-2026. Your Java names and the JSON an API expects do not always match.
@JsonProperty: snake_case JSON names on camelCase fields
Annotation is a small label, written with @, that you put on a class, field or record component to give it extra meaning. Jackson annotations change how one property is written or read.
A partner's API uses snake_case names, while Java uses camelCase. The program renames two fields with one annotation each.
Example 1 · JsonPropertyDemo.java: snake_case names for a partner
Runs in: the json-playground Maven project with Jackson 3.1.5
import com.fasterxml.jackson.annotation.JsonProperty;import tools.jackson.databind.json.JsonMapper;
public class JsonPropertyDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
// Java names stay camelCase; the JSON names follow the partner's snake_case record CustomerDto(@JsonProperty("customer_id") Integer customerId, @JsonProperty("full_name") String fullName, String email) { }
public static void main(String[] args) { CustomerDto asha = new CustomerDto(1, "Asha Rao", "asha.rao@example.com"); System.out.println(MAPPER.writeValueAsString(asha));
String fromPartner = "{\"customer_id\": 2, \"full_name\": \"Ravi Kumar\", \"email\": \"ravi.kumar@example.com\"}"; CustomerDto ravi = MAPPER.readValue(fromPartner, CustomerDto.class); System.out.println(ravi.fullName() + " has id " + ravi.customerId());
// The camelCase name is no longer a known property CustomerDto wrong = MAPPER.readValue("{\"customerId\": 3, \"fullName\": \"Meena Iyer\"}", CustomerDto.class); System.out.println("Read with camelCase keys: " + wrong); }}{"customer_id":1,"full_name":"Asha Rao","email":"asha.rao@example.com"}
Ravi Kumar has id 2
Read with camelCase keys: CustomerDto[customerId=null, fullName=null, email=null]What this code does
customerIdandfullNameare written ascustomer_idandfull_name;emailhas no annotation and keeps its name.- Reading the partner's snake_case JSON fills the record. The last read used the old camelCase keys: they no longer match, Jackson 3 skips unknown keys, and every field is
null. The next-but-one lesson shows how to make that an error.
@JsonProperty("name") gives one property a different JSON name. Java code uses camelCase (fullName), while many APIs, especially ones written in Python or Ruby, use snake_case (full_name); the annotation lets each side keep its own style.
The new name works in both directions. JSON that still uses fullName no longer matches, and because Jackson 3 ignores unknown keys by default, the value is silently left null. On a record, put the annotation on the component in the header.
com.fasterxml.jackson.annotation in both Jackson 2 and Jackson 3.@JsonIgnore: keeping secrets such as password hashes out of JSON
@JsonIgnore removes a property from JSON completely: it is never written, and a value for it in incoming JSON is never read. Use it for data that must not leave the server, such as a password hash.
A response must never show a password hash, while a sign-up form must still accept a password. The program handles both.
Example 2 · JsonIgnoreDemo.java: a hidden hash and a write-only password
Runs in: the json-playground Maven project with Jackson 3.1.5
import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonProperty;import tools.jackson.databind.json.JsonMapper;
public class JsonIgnoreDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
// Loaded from the database; the hash must never leave the server record UserAccount(int id, String email, @JsonIgnore String passwordHash) { }
// Sent by the sign-up form: the password may come IN, but never goes OUT record SignUpRequest(String email, @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String password) { }
public static void main(String[] args) { UserAccount user = new UserAccount(7, "divya.nair@example.com", "$2a$10$Qm5vZ8xY0u1Hc3"); System.out.println("Response: " + MAPPER.writeValueAsString(user));
UserAccount fromJson = MAPPER.readValue( "{\"id\": 7, \"email\": \"divya.nair@example.com\", \"passwordHash\": \"hacked\"}", UserAccount.class); System.out.println("Read back, hash = " + fromJson.passwordHash());
SignUpRequest form = MAPPER.readValue( "{\"email\": \"imran.khan@example.com\", \"password\": \"Campus@2026\"}", SignUpRequest.class); System.out.println("Password received: " + (form.password() != null)); System.out.println("Logged as: " + MAPPER.writeValueAsString(form)); }}Response: {"id":7,"email":"divya.nair@example.com"}
Read back, hash = null
Password received: true
Logged as: {"email":"imran.khan@example.com"}What this code does
- The response has no
passwordHash. When a client sends one, Jackson ignores it, so nobody can set the hash through JSON. - The sign-up password was read (
true), but writing the same object, as a log statement might, leaves it out. That is whatWRITE_ONLYmeans.
Use @JsonIgnore for a password hash, an OTP or an internal cost price: one forgotten field in a response is a real security leak, because anyone can see the JSON in the browser's network tab.
Sometimes a value must come in but never go out, like the password in a sign-up form. @JsonIgnore would drop it on reading too, so use @JsonProperty(access = JsonProperty.Access.WRITE_ONLY): Jackson reads it, but never writes it. The name is from the client's point of view: the client may only write it.
Find the bug
Find the field that leaks
Select the line that is wrong.
This record is sent to the browser. Tap the line that leaks a secret.
Round 1 of 3@JsonIgnore is the second line of defence.@JsonInclude(NON_NULL): leaving out empty fields
@JsonInclude tells Jackson which properties to write. NON_NULL leaves out properties whose value is null; NON_EMPTY also leaves out empty strings, lists and maps.
A customer without a phone number appears as "phone":null. The program writes the same record plainly, with NON_NULL and with NON_EMPTY.
Example 3 · JsonIncludeDemo.java: null and empty fields
Runs in: the json-playground Maven project with Jackson 3.1.5
import com.fasterxml.jackson.annotation.JsonInclude;import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class JsonIncludeDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
record CustomerPlain(String fullName, String phone, List<String> tags) { }
@JsonInclude(JsonInclude.Include.NON_NULL) record CustomerNonNull(String fullName, String phone, List<String> tags) { }
@JsonInclude(JsonInclude.Include.NON_EMPTY) record CustomerNonEmpty(String fullName, String phone, List<String> tags) { }
public static void main(String[] args) { // Meena has no phone number and no tags System.out.println(MAPPER.writeValueAsString(new CustomerPlain("Meena Iyer", null, List.of()))); System.out.println(MAPPER.writeValueAsString(new CustomerNonNull("Meena Iyer", null, List.of()))); System.out.println(MAPPER.writeValueAsString(new CustomerNonEmpty("Meena Iyer", null, List.of())));
// The same rule for every class, set once on the mapper JsonMapper skipNulls = JsonMapper.builder() .changeDefaultPropertyInclusion(incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL)) .build(); System.out.println(skipNulls.writeValueAsString(new CustomerPlain("Meena Iyer", null, List.of()))); }}{"fullName":"Meena Iyer","phone":null,"tags":[]}
{"fullName":"Meena Iyer","tags":[]}
{"fullName":"Meena Iyer"}
{"fullName":"Meena Iyer","tags":[]}What this code does
- Plain: everything is written.
NON_NULLdroppedphone.NON_EMPTYdropped the emptytagslist as well. - The last line used a mapper-wide
NON_NULLrule on the plain record, with no annotation on the record at all.
By default Jackson writes every property. Put @JsonInclude(JsonInclude.Include.NON_NULL) on a class or record to shorten responses, but remember it changes the contract: the client must treat a missing key the same as null.
To use one rule for every class, set it once on the mapper with changeDefaultPropertyInclusion(...) instead of annotating each class.
@JsonFormat for a custom date pattern
@JsonFormat sets the text format of one date, time or number property, in both directions. @JsonFormat(pattern = "dd-MM-yyyy") makes a date use day-month-year.
An older booking partner sends dates as 02-11-2026. The program reads and writes them with one pattern.
Example 4 · JsonFormatDemo.java: Indian-style dates from a booking partner
Runs in: the json-playground Maven project with Jackson 3.1.5
import com.fasterxml.jackson.annotation.JsonFormat;import java.math.BigDecimal;import java.time.LocalDate;import java.time.LocalDateTime;import tools.jackson.databind.json.JsonMapper;
public class JsonFormatDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
// An older booking partner sends Indian-style dates and prices as text record Booking(String pnr, @JsonFormat(pattern = "dd-MM-yyyy") LocalDate journeyDate, @JsonFormat(pattern = "dd-MM-yyyy HH:mm") LocalDateTime bookedAt, @JsonFormat(shape = JsonFormat.Shape.STRING) BigDecimal fare) { }
public static void main(String[] args) { String json = """ {"pnr": "4521367890", "journeyDate": "02-11-2026", "bookedAt": "16-10-2026 09:15", "fare": "1450.50"} """; Booking b = MAPPER.readValue(json, Booking.class); System.out.println("Journey on " + b.journeyDate().getDayOfWeek() + ", " + b.journeyDate()); System.out.println("Written back: " + MAPPER.writeValueAsString(b)); }}Journey on MONDAY, 2026-11-02
Written back: {"pnr":"4521367890","journeyDate":"02-11-2026","bookedAt":"16-10-2026 09:15","fare":"1450.50"}What this code does
"02-11-2026"was read as 2 November 2026 (a Monday) because of the pattern; without it, Jackson would reject the text as not ISO-8601.- Writing uses the same patterns, and the fare stays a string
"1450.50"because ofShape.STRING.
The pattern letters are the same as in DateTimeFormatter: dd day, MM month, yyyy year, HH hour, mm minute. Use a custom pattern when an older partner system insists on its own format.
@JsonFormat(shape = JsonFormat.Shape.STRING) on a BigDecimal writes the number as a string, such as "1450.50", for clients that read numbers as doubles. Keep ISO-8601 for your own APIs; custom patterns are for fitting into someone else's.
Naming strategies on the mapper versus per-field annotations
Naming strategy is a rule set once on the mapper that renames every property of every class, for example turning unitPrice into unit_price with SNAKE_CASE.
One setting on the mapper renames every property. The program also shows one field that keeps its own explicit name.
Example 5 · NamingStrategyDemo.java: snake_case for a whole API
Runs in: the json-playground Maven project with Jackson 3.1.5
import com.fasterxml.jackson.annotation.JsonProperty;import java.math.BigDecimal;import tools.jackson.databind.PropertyNamingStrategies;import tools.jackson.databind.json.JsonMapper;
public class NamingStrategyDemo {
// Every class this mapper touches gets snake_case names, with no annotations static final JsonMapper SNAKE = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) .build();
record ProductDto(int productId, String sku, BigDecimal unitPrice, int stockLeft) { }
record CategoryDto(int categoryId, @JsonProperty("title") String name, Integer parentId) { }
public static void main(String[] args) { System.out.println(SNAKE.writeValueAsString( new ProductDto(7, "ACC-PB20K", new BigDecimal("2199.00"), 60)));
// An explicit @JsonProperty name wins over the strategy System.out.println(SNAKE.writeValueAsString(new CategoryDto(2, "Mobiles", 1)));
ProductDto back = SNAKE.readValue( "{\"product_id\": 8, \"sku\": \"ACC-M331\", \"unit_price\": 849.00, \"stock_left\": 0}", ProductDto.class); System.out.println(back); }}{"product_id":7,"sku":"ACC-PB20K","unit_price":2199.00,"stock_left":60}
{"category_id":2,"title":"Mobiles","parent_id":1}
ProductDto[productId=8, sku=ACC-M331, unitPrice=849.00, stockLeft=0]What this code does
- No annotations on
ProductDto, yet every name is snake_case, in both directions. - On
CategoryDtothe explicit@JsonProperty("title")won over the strategy, whilecategoryIdandparentIdwere still converted.
Set it once on the builder with propertyNamingStrategy(...). Other strategies include KEBAB_CASE (unit-price) and UPPER_CAMEL_CASE (UnitPrice).
Choose by scope. When a whole API uses one style, set the strategy on the mapper: no annotations to forget. When only a few fields differ, or a name is not a mechanical conversion (such as name to title), use @JsonProperty; an explicit name always wins over the strategy.
Next step
Check your understanding
11 quick questions