Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Teams write API DTOs as mutable beans, Lombok builders, and records in the same code base, and deserialization bugs keep appearing. What standard would you set?

I would make records the default for request and response DTOs, because they are immutable and Jackson handles them without annotations. Builders with @JsonDeserialize(builder = ...) are allowed only for large DTOs with many optional fields, validation lives in compact constructors or Bean Validation, and JPA entities never take part in API binding. Every DTO gets a round-trip test, and where the contract demands it, deserialization fails on unknown or missing required properties.

Why this question is asked

When one code base mixes mutable beans, Lombok builders and records, each style has its own way to go wrong with Jackson: a bean missing a setter silently drops a field, a builder without the right annotation fails with a confusing error, a record works perfectly. Developers copy whatever style is nearest, so the bugs keep coming. Interviewers ask this standard-setting question to see whether we can turn many small bugs into one clear rule. In this answer, we will see the typical bugs of each style, then set the standard step by step: records first, builders as a documented exception, validation, entities out, and tests that enforce the contract.

1The Bugs Each Style Produces

Mutable beans rely on a default constructor and setters. Forget a setter, or name it slightly differently from the field, and Jackson either ignores the property when unknown fields are allowed, or fails when they are not. Beans can also be left half-filled, and nothing stops code from changing them after validation.

Lombok builders produce immutable objects, but Jackson does not know how to use a builder unless we tell it. A plain @Builder class without a no-argument constructor fails with Cannot construct instance. Adding @NoArgsConstructor and @Setter to make it work quietly turns it back into a mutable bean. Records, finally, are immutable, have a canonical constructor Jackson uses directly since 2.12, and keep their component names, so they mostly just work.

Java
@Builder @Getter
public class CreateOrderRequest { // Lombok builder, no Jackson hints
private final String customerId;
private final List<OrderLine> lines;
}
mapper.readValue(json, CreateOrderRequest.class);
// InvalidDefinitionException: Cannot construct instance of `CreateOrderRequest`
public record CreateOrderRequest(String customerId, List<OrderLine> lines) {}
mapper.readValue(json, CreateOrderRequest.class); // works, no annotations
DTO styles and how they fail with Jackson
StyleTypical failureVerdict for API DTOs
Mutable beanMissing or misnamed setter drops dataAvoid for new code
Lombok @Builder aloneCannot construct instanceOnly with @Jacksonized or @JsonDeserialize
Lombok @Value with @Builder and @JacksonizedWorks; hidden generated codeAllowed for large optional DTOs
RecordRare; missing fields become nullDefault choice

2Rule 1: Records for Request and Response DTOs

The standard starts with one sentence: API DTOs are records unless there is a written reason. Records are immutable, so a validated request cannot change later. They have value-based equals and hashCode, which makes tests simple. They need no annotations for Jackson, so there is nothing to forget. And they make the JSON contract visible in one line, which helps reviewers spot changes.

Records do not solve everything. Missing properties still become null, and very wide DTOs with twenty optional fields become unreadable to construct in code. The next rules cover those cases.

3Rule 2: Builders Only for Large Optional-Field DTOs

Some DTOs, such as a search request with fifteen optional filters, are painful to create through a constructor with fifteen arguments. For those, a builder is allowed, but it must be wired for Jackson explicitly. With plain Jackson that means @JsonDeserialize(builder = ...) on the class and @JsonPOJOBuilder on the builder; with Lombok, @Jacksonized on a @Builder class generates the same annotations.

Java
@JsonDeserialize(builder = SearchRequest.Builder.class)
public final class SearchRequest {
private final String text; private final Integer minPrice; private final Integer maxPrice;
private SearchRequest(Builder b) { text = b.text; minPrice = b.minPrice; maxPrice = b.maxPrice; }
public String getText() { return text; }
public Integer getMinPrice() { return minPrice; }
public Integer getMaxPrice() { return maxPrice; }
@JsonPOJOBuilder(withPrefix = "") // methods are text(...), not withText(...)
public static final class Builder {
private String text; private Integer minPrice; private Integer maxPrice;
public Builder text(String v) { text = v; return this; }
public Builder minPrice(Integer v) { minPrice = v; return this; }
public Builder maxPrice(Integer v) { maxPrice = v; return this; }
public SearchRequest build() { return new SearchRequest(this); }
}
}
mapper.readValue("{\"text\":\"lamp\",\"maxPrice\":50}", SearchRequest.class);
// SearchRequest text=lamp, minPrice=null, maxPrice=50
// Lombok equivalent
@Value @Builder @Jacksonized
public class SearchRequest { String text; Integer minPrice; Integer maxPrice; }

Notice withPrefix = "". Jackson's default builder methods start with with, as in withText, while Lombok and most hand-written builders use bare names. Forgetting this setting is one of the classic builder bugs, and @Jacksonized sets it for us.

4Rule 3: Validation in One Agreed Place

Validation should not depend on the DTO style. The standard says that rules about the input, such as required fields, lengths, ranges and formats, are expressed with Bean Validation annotations on record components, checked by @Valid on the controller parameter, which gives a 400 with field-level messages. Invariants that must hold for any instance, even one created in code, go in the record's compact constructor.

Java
public record CreateCustomerRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email) {
public CreateCustomerRequest {
email = email == null ? null : email.trim().toLowerCase(Locale.ROOT); // normalise
}
}

5Rule 4: Keep Entities Out of API Binding

JPA entities never appear as @RequestBody parameters or as response bodies. Binding requests directly to entities lets clients set fields they should not, such as id, status or price, a problem known as mass assignment. Serializing entities as responses can trigger lazy loading of associations, cause infinite recursion on bidirectional relations, and expose internal columns. Every endpoint has its own request and response records, and a mapper class or MapStruct converts between them and the entities. An ArchUnit test that forbids @Entity types in controller method signatures enforces the rule cheaply.

6Rule 5: Round-Trip and Contract Tests

Finally, tests make the standard stick. Every DTO gets a round-trip test that serializes an example with the application's mapper, compares it with a stored JSON file, and reads it back to an equal object. For records, equality is free; for builders it shows whether the builder is wired correctly. Where the contract requires strictness, typically on public commands, the mapper or a specific ObjectReader enables FAIL_ON_UNKNOWN_PROPERTIES and FAIL_ON_MISSING_CREATOR_PROPERTIES or FAIL_ON_NULL_CREATOR_PROPERTIES, and the tests include a payload with a typo that must fail.

Java
@Test
void createCustomerRequestRoundTrip() throws Exception {
var dto = new CreateCustomerRequest("Ann", "a@x.com");
String json = mapper.writeValueAsString(dto);
JSONAssert.assertEquals(read("dto/create-customer.json"), json, true); // shape unchanged
assertEquals(dto, mapper.readValue(json, CreateCustomerRequest.class)); // round trip
}

With these five rules written on one page, with examples, new code converges on records, the remaining builders are correct by construction, and the bugs that came from style mixing stop appearing.

7Follow-up questions

Should we convert all existing beans to records at once?

No. I would apply the standard to new DTOs and to DTOs we touch anyway, with the round-trip tests protecting the JSON shape during each conversion. A mass rewrite risks changing contracts for no immediate gain.

Are records a problem for frameworks that need setters?

For Jackson and Spring MVC, no. Some older libraries and form binding expect beans, and JPA entities cannot be records because they need a no-argument constructor and mutable state. That is another reason to keep entities and DTOs separate.

How do you handle a PATCH request with records?

A record cannot tell a missing field from an explicit null, because both become null. For PATCH I would use a JsonNode or a JSON Merge Patch document, or a DTO with Optional-like wrapper fields, and apply only the fields that are present.

8Conclusion

In this answer, we saw how mutable beans, Lombok builders and records each fail differently with Jackson, and we set a standard: records for request and response DTOs, builders with @JsonDeserialize(builder = ...) or @Jacksonized only for large optional-field DTOs, validation in compact constructors and Bean Validation, entities kept out of API binding, and round-trip tests with strict failure on unknown or missing properties where the contract requires it.

What to say in the interviewAbout 80 seconds aloud

Open with

I would set a short standard with one default and a few documented exceptions. The default is records for request and response DTOs: they are immutable, they keep their component names, and Jackson handles them since 2.12 through the canonical constructor with no annotations, so there is nothing to forget.

Then, if they want more

The exception is large DTOs with many optional fields, like a search request with fifteen filters; those may use builders, but wired explicitly with JsonDeserialize builder and JsonPOJOBuilder with an empty prefix, or Lombok's Jacksonized, because a plain Lombok Builder fails with cannot construct instance. Mutable beans are avoided in new code.

Validation lives in one agreed place: Bean Validation annotations on record components with Valid on the controller for input rules, and compact constructors for invariants and normalisation. Entities never take part in API binding, both to prevent mass assignment and to avoid lazy loading and recursion in responses, and an ArchUnit test enforces that.

Finally, every DTO has a round-trip test against a stored JSON file, and for strict contracts the mapper fails on unknown or missing required properties, with a test that sends a typo. That turns many small bugs into one rule people can follow.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Teams write API DTOs as mutable beans, Lombok builders, and records in the same code...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/1c512675d0/