JSON to Java: records, POJOs, Jackson and Gson

Mapping a JSON payload to Java takes three decisions: the shape of the class, the library that reads it, and what happens when the JSON does not match.

3 min readUpdated MasterDev

Records or POJOs

If you are on Java 16 or later, start with a record. It is immutable, has equals, hashCode and toString for free, and takes a fraction of the lines. Jackson reads records since version 2.12 and Gson since 2.10.

Generated by the json.foo converter
public record User(
    @JsonProperty("id") int id,
    @JsonProperty("full-name") String fullName,
    @JsonProperty("address") Address address,
    @JsonProperty("orders") List<Order> orders
) {}

Choose a POJO (a class with fields, getters and setters) when you are on Java 8 or 11, when a framework needs a no-argument constructor, or when the object must change after it is read. Lombok can remove most of the boilerplate; see below.

Reading with Jackson

Jackson is the default in Spring Boot and the most common choice elsewhere.

ObjectMapper mapper = new ObjectMapper();

User user = mapper.readValue(json, User.class);

// Lists need a TypeReference, because generics are erased at runtime
List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {});

String back = mapper.writeValueAsString(user);

Create the ObjectMapper once and reuse it: it is thread-safe once configured, and building one is expensive. In Spring Boot, inject the one the framework already configured.

Reading with Gson

Gson gson = new Gson();

User user = gson.fromJson(json, User.class);
List<User> users = gson.fromJson(json, new TypeToken<List<User>>() {}.getType());

Gson is small and has no dependencies, which makes it popular on Android. It uses @SerializedName("full-name") where Jackson uses @JsonProperty. The converter writes either one, depending on the Library option.

Field names

JSON keys such as created_at or full-name do not follow Java naming. You can annotate every field, as the converter does by default, or set a naming strategy once and skip most annotations:

// Jackson 2.12+
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

// Gson
Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create();

A global strategy is less noise, but annotations survive refactors: renaming a Java field cannot silently break the mapping. Turn off Annotate every field in the converter if you prefer the strategy.

Missing and null values

A primitive such as int cannot hold null. When the key is missing or null, Jackson leaves it as 0 by default, so you cannot tell "zero" from "not sent". That is why the converter uses Integer, Double and Boolean for fields that are optional or nullable in your sample, and primitives for the rest.

Avoid Optional<T> as a field or record component type in DTOs. It needs an extra Jackson module, and it was designed as a return type. Keep the field nullable and wrap it in Optional in a method if you want to.

Fields your class does not have

Plain Jackson throws UnrecognizedPropertyException when the JSON contains a key the class lacks. That is strict, and it breaks your client the day the API adds a field. Two ways out:

// Per class (the converter's "Ignore unknown fields" option)
@JsonIgnoreProperties(ignoreUnknown = true)
public record User(...) {}

// For the whole mapper
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Spring Boot's auto-configured ObjectMapper already turns this check off, and Gson ignores unknown keys by default.

Dates, money and enums

The converter types dates as String, because JSON has no date type and it will not guess the format. Change them by hand:

  • Dates: use Instant or OffsetDateTime for ISO 8601 timestamps and LocalDate for plain dates. Jackson needs the jackson-datatype-jsr310 module (mapper.registerModule(new JavaTimeModule())); Spring Boot registers it for you.
  • Money: replace double with BigDecimal. Jackson reads JSON numbers into BigDecimal without passing through a double, so no cents are lost.
  • Fixed values: a status field that is always "PAID", "PENDING" or "FAILED" reads straight into an enum.

POJOs with Lombok

With Style: POJO, the converter can add Lombok. @Data generates getters, setters, equals, hashCode and toString. If you add @Builder, Jackson also needs a no-argument constructor to create the object, so the converter adds @NoArgsConstructor and @AllArgsConstructor too. With records you do not need Lombok at all.

A workflow that holds up

  1. Save a real response from the API as src/test/resources/user.json.
  2. Check it in the formatter.
  3. Generate the classes in the converter with Java, your library and your package name.
  4. Fix dates, money and enums by hand.
  5. Write one test that reads user.json into User. When the API changes, that test fails before your users notice.