JSON guide · 2 min read
How to Generate Java Classes from JSON
Generate Java records or DTO classes from JSON and review nullability, numeric precision, collections, naming and deserialization behavior.
Choose records or classes from the use case
Java records are concise for immutable data carriers and work well for many API DTOs. Mutable classes may still be required by project conventions, frameworks, custom construction or inheritance-heavy designs.
Map external property names explicitly
snake_case JSON names and Java camelCase fields can be handled with a naming strategy or annotations such as JsonProperty. Make the mapping obvious when external names form part of a stable contract.
public record User(
@JsonProperty("user_id") String userId,
String name
) {}Review nullability rather than trusting generated reference types
A generated String field can still receive null. Decide whether null is legal, whether omission is legal and which validation annotations or domain types express those expectations in your project.
Choose numeric types from domain requirements
Do not infer int, long, BigInteger or BigDecimal solely from one observed value. Identifiers may be strings, while money and high-precision measurements frequently need BigDecimal rather than double.
Check collection element types with more than one record
An empty array reveals no element type, and mixed data can push generation toward Object. Use documentation and representative cases to model List<T> correctly.
Test with the production serializer configuration
Generated code can compile yet fail deserialization because the real ObjectMapper uses naming strategies, custom modules, strict unknown-field rules or date handling. Tests should use the same configuration as the application boundary.
- Missing required fields.
- Explicit nulls.
- Unknown extra fields.
- Large numbers and decimals.
- Empty collections.
- Naming and date-time formats.
Common questions
Frequently asked questions
Should generated Java DTOs use records?
Records are a strong fit for many immutable DTOs, but project conventions and framework requirements should determine the final design.
Why can deserialization fail when the generated class looks correct?
The real payload or ObjectMapper settings may differ in nulls, property names, unknown fields, types or date handling.
Should money be generated as double?
Usually not when exact decimal arithmetic matters. BigDecimal is commonly more appropriate for monetary values.