Records, dates and money
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop's API carries who ordered, what, how much and when. Money must never drift by a paisa, and a date must mean the same moment in every country, so these simple values need special care.
Records as DTOs: Jackson reads and writes them with no extra code
DTO (data transfer object) is a small class whose only job is to carry data across a boundary, such as an API request or response. A Java record makes a short, safe DTO.
A product DTO is written as a record in one line. The program writes it to JSON and reads it back.
Example 1 · RecordDtoDemo.java: a product DTO as a record
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.math.BigDecimal;import tools.jackson.databind.json.JsonMapper;
public class RecordDtoDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
// A DTO in one line: no getters, setters or no-arg constructor needed record ProductDto(String sku, String name, String category, BigDecimal price, int stock) { }
public static void main(String[] args) { ProductDto cooker = new ProductDto("HK-COOK3L", "Prestige Pressure Cooker 3L", "Home & Kitchen", new BigDecimal("1899.00"), 15);
String json = MAPPER.writeValueAsString(cooker); System.out.println(json);
ProductDto back = MAPPER.readValue(json, ProductDto.class); System.out.println(back); System.out.println("Same values: " + back.equals(cooker)); }}{"sku":"HK-COOK3L","name":"Prestige Pressure Cooker 3L","category":"Home & Kitchen","price":1899.00,"stock":15}
ProductDto[sku=HK-COOK3L, name=Prestige Pressure Cooker 3L, category=Home & Kitchen, price=1899.00, stock=15]
Same values: trueWhat this code does
- The keys follow the record's component order (
sku,name,category,price,stock), not alphabetical order as with the getter classes earlier. - Reading called the record's constructor with all five values. The generated
equalsconfirms that the round trip lost nothing.
Java generates the constructor, accessors, equals, hashCode and toString for a record. Jackson 3 writes each component (a value in the record header) as a property, in the order they are declared, and reads JSON by calling the constructor with all the values.
No getters, setters or no-arg constructor are needed, and the result cannot be changed after it is created.
LocalDate, LocalDateTime and Instant as ISO-8601 strings, not number arrays
ISO-8601 is the standard text form for dates and times, such as 2026-09-24 or 2026-09-22T02:40:00Z. Jackson 3 writes and reads java.time values in this form.
Three java.time values are written to JSON and read back. A second program shows the number-array style of older code.
Example 2 · DatesDemo.java: java.time values as ISO-8601 text
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.time.Instant;import java.time.LocalDate;import java.time.LocalDateTime;import tools.jackson.databind.json.JsonMapper;
public class DatesDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
record Delivery(int orderId, LocalDate expectedOn, LocalDateTime packedAt, Instant shippedAt) { }
public static void main(String[] args) { Delivery d = new Delivery(14, LocalDate.of(2026, 9, 24), LocalDateTime.of(2026, 9, 22, 7, 30), Instant.parse("2026-09-22T02:40:00Z"));
String json = MAPPER.writeValueAsString(d); System.out.println(json);
Delivery back = MAPPER.readValue(json, Delivery.class); System.out.println("Expected on a " + back.expectedOn().getDayOfWeek()); System.out.println("Equal after the round trip: " + back.equals(d)); }}{"orderId":14,"expectedOn":"2026-09-24","packedAt":"2026-09-22T07:30:00","shippedAt":"2026-09-22T02:40:00Z"}
Expected on a THURSDAY
Equal after the round trip: trueWhat this code does
- Each type has its own ISO form: a date, a date-time without zone, and an
Instantending inZfor UTC. - Reading back gives real
java.timeobjects, sogetDayOfWeek()works and the record equals the original.
Example 3 · DateArraysDemo.java: the number-array style of older code
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.time.LocalDate;import java.time.LocalDateTime;import tools.jackson.databind.cfg.DateTimeFeature;import tools.jackson.databind.json.JsonMapper;
public class DateArraysDemo {
record Delivery(int orderId, LocalDate expectedOn, LocalDateTime packedAt) { }
public static void main(String[] args) { Delivery d = new Delivery(14, LocalDate.of(2026, 9, 24), LocalDateTime.of(2026, 9, 22, 7, 30));
// What Jackson 2 with the date module does by default: dates as numbers JsonMapper timestamps = JsonMapper.builder() .enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS) .build(); System.out.println("As timestamps: " + timestamps.writeValueAsString(d));
// Jackson 3's default: ISO-8601 strings JsonMapper iso = JsonMapper.builder().build(); System.out.println("As ISO text: " + iso.writeValueAsString(d)); }}As timestamps: {"orderId":14,"expectedOn":[2026,9,24],"packedAt":[2026,9,22,7,30]}
As ISO text: {"orderId":14,"expectedOn":"2026-09-24","packedAt":"2026-09-22T07:30:00"}What this code does
- With
WRITE_DATES_AS_TIMESTAMPSon, the date became[2026,9,24]: the default you will meet in Jackson 2 projects that use the date module. - The ISO text is what APIs should send. Jackson 3 can still read the array form, which helps when an older service sends it.
Jackson 3 writes LocalDate as "2026-09-24", LocalDateTime as "2026-09-22T07:30:00" and Instant as "2026-09-22T02:40:00Z", and reads the same strings back.
Older code behaves differently. Jackson 2 needs the extra jackson-datatype-jsr310 module for these types; without it, writing a LocalDate fails with Java 8 date/time type java.time.LocalDate not supported by default. With the module, Jackson 2 writes dates as number arrays such as [2026,9,24], which JavaScript clients and people reading logs cannot use easily. In Jackson 3 that style is only a setting, DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, and it is off.
Time zones and offsets in JSON timestamps
Offset is the difference from UTC, the world's reference clock; India is +05:30. A date-time with an offset, or a Z for UTC, names one exact moment.
A payment is made at 9:05 PM in India. The program shows how the offset, UTC and a time zone change what is printed.
Example 4 · TimeZoneDemo.java: offsets, UTC and India time
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.time.Instant;import java.time.OffsetDateTime;import java.time.ZoneId;import java.time.format.DateTimeFormatter;import java.util.Locale;import tools.jackson.databind.cfg.DateTimeFeature;import tools.jackson.databind.json.JsonMapper;
public class TimeZoneDemo {
static final ZoneId INDIA = ZoneId.of("Asia/Kolkata"); static final DateTimeFormatter SHOW = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a", Locale.ENGLISH);
record Payment(String upiRef, OffsetDateTime paidAt) { } record PaymentUtc(String upiRef, Instant paidAt) { }
public static void main(String[] args) { String json = "{\"upiRef\": \"UPI123456\", \"paidAt\": \"2026-09-21T21:05:00+05:30\"}";
JsonMapper mapper = JsonMapper.builder().build(); Payment p = mapper.readValue(json, Payment.class); System.out.println("Default read: " + p.paidAt());
JsonMapper keepOffset = JsonMapper.builder() .disable(DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .build(); System.out.println("Offset kept: " + keepOffset.readValue(json, Payment.class).paidAt()); System.out.println("Same moment: " + p.paidAt().isEqual(keepOffset.readValue(json, Payment.class).paidAt()));
// Store and send an Instant (UTC); turn it into India time only to show it to a person PaymentUtc utc = mapper.readValue(json, PaymentUtc.class); System.out.println("As Instant: " + utc.paidAt()); System.out.println("Shown in India: " + utc.paidAt().atZone(INDIA).format(SHOW)); }}Default read: 2026-09-21T15:35Z Offset kept: 2026-09-21T21:05+05:30 Same moment: true As Instant: 2026-09-21T15:35:00Z Shown in India: 21 Sep 2026, 09:05 PM
What this code does
- By default the
+05:30time came back as15:35Z, the same moment in UTC. With the feature disabled, the offset was kept;isEqualconfirms both are the same instant. - Reading straight into an
Instantstores the moment in UTC.atZone(Asia/Kolkata)turns it back into 9:05 PM for the person who paid.Locale.ENGLISHkeeps the month and AM/PM text the same on every computer.
A LocalDateTime such as "2026-09-21T21:05:00" has no offset, so a server in another country cannot know which moment it means. For real events such as payments and orders, use Instant (always UTC, written with Z) or OffsetDateTime (with its offset).
Jackson converts an OffsetDateTime it reads to UTC by default, so 21:05+05:30 comes back as 15:35Z: the same moment, different text. Disable DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE to keep the original offset. A simple rule: store and send Instant, and convert to India time (Asia/Kolkata) only when you show it to a person.
BigDecimal prices: keeping exact values
BigDecimal stores decimal numbers exactly, digit by digit, and keeps its scale (the digits after the point), so 17999.00 stays 17999.00. Use it for every price and amount.
A cart total as a double drifts; as a BigDecimal it stays exact. The program adds the same cart both ways.
Example 5 · MoneyDemo.java: double drift versus exact BigDecimal
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.math.BigDecimal;import java.util.List;import java.util.Map;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
public class MoneyDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
record LineAsDouble(String sku, double price, int qty) { } record LineAsDecimal(String sku, BigDecimal price, int qty) { }
public static void main(String[] args) { String cart = """ [{"sku": "BK-ATOMIC", "price": 399.10, "qty": 3}, {"sku": "ACC-USBC1", "price": 199.10, "qty": 3}] """;
double doubleTotal = 0; for (LineAsDouble l : MAPPER.readValue(cart, new TypeReference<List<LineAsDouble>>() { })) { doubleTotal += l.price() * l.qty(); } System.out.println("double total: " + doubleTotal);
BigDecimal exactTotal = BigDecimal.ZERO; for (LineAsDecimal l : MAPPER.readValue(cart, new TypeReference<List<LineAsDecimal>>() { })) { exactTotal = exactTotal.add(l.price().multiply(BigDecimal.valueOf(l.qty()))); } System.out.println("BigDecimal total: " + exactTotal);
// Big numbers in a Map: Double by default, BigDecimal when you ask for it String yearly = "{\"upiVolume\": 198765432109876.54}"; Map<?, ?> asDouble = MAPPER.readValue(yearly, Map.class); System.out.println("Map default: " + asDouble.get("upiVolume")); JsonMapper exact = MAPPER.rebuild().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS).build(); Map<?, ?> asDecimal = exact.readValue(yearly, Map.class); System.out.println("BIG_DECIMAL on: " + asDecimal.get("upiVolume")); }}double total: 1794.6000000000001 BigDecimal total: 1794.60 Map default: 1.9876543210987653E14 BIG_DECIMAL on: 198765432109876.54
What this code does
- The same cart gives
1794.6000000000001withdoubleand exactly1794.60withBigDecimal. Only the field type changed. - Read into a
Map, the large decimal became aDoubleand lost its last digits. WithUSE_BIG_DECIMAL_FOR_FLOATSthe map holds the exactBigDecimal.
A double stores a binary approximation, so 0.1, 199.10 and most other prices are slightly off, and the errors grow when you multiply and add: a cart total can come out as 1794.6000000000001.
Declare money fields as BigDecimal in your records. Jackson then reads 399.10 exactly and accepts the price as a number or a string. When you read into a Map or JsonNode there is no field type to guide it, so decimals become Double by default; DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS makes them BigDecimal instead.
Enums such as order status as JSON strings
Enum is a fixed set of named constants, such as OrderStatus. Jackson writes a constant by its name, so SHIPPED becomes "SHIPPED", and reads the same name back.
Order status is an enum. The program writes one status and tries to read two values that are not valid.
Example 6 · EnumDemo.java: order status as a string
Runs in: the json-playground Maven project with Jackson 3.1.5
import tools.jackson.core.JacksonException;import tools.jackson.databind.MapperFeature;import tools.jackson.databind.json.JsonMapper;
public class EnumDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
enum OrderStatus { PLACED, SHIPPED, DELIVERED, CANCELLED }
record OrderSummary(int orderId, OrderStatus status) { }
static void tryRead(JsonMapper mapper, String json) { try { System.out.println("Read: " + mapper.readValue(json, OrderSummary.class)); } catch (JacksonException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getOriginalMessage()); } }
public static void main(String[] args) { System.out.println(MAPPER.writeValueAsString(new OrderSummary(14, OrderStatus.SHIPPED)));
tryRead(MAPPER, "{\"orderId\": 15, \"status\": \"PLACED\"}"); tryRead(MAPPER, "{\"orderId\": 16, \"status\": \"RETURNED\"}"); tryRead(MAPPER, "{\"orderId\": 17, \"status\": \"shipped\"}");
JsonMapper lenient = MAPPER.rebuild().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS).build(); tryRead(lenient, "{\"orderId\": 17, \"status\": \"shipped\"}"); }}{"orderId":14,"status":"SHIPPED"}
Read: OrderSummary[orderId=15, status=PLACED]
InvalidFormatException: Cannot deserialize value of type `EnumDemo$OrderStatus` from String "RETURNED": not one of the values accepted for Enum class: [CANCELLED, SHIPPED, DELIVERED, PLACED]
InvalidFormatException: Cannot deserialize value of type `EnumDemo$OrderStatus` from String "shipped": not one of the values accepted for Enum class: [CANCELLED, SHIPPED, DELIVERED, PLACED]
Read: OrderSummary[orderId=17, status=SHIPPED]What this code does
SHIPPEDwas written as the string"SHIPPED", and"PLACED"was read back as the constant."RETURNED"is not a constant, and"shipped"has the wrong case; both fail with a message that lists the accepted values. The lenient copy of the mapper accepts any case.
A fixed set of values in an enum is safer than a free String field: a value the program does not know is rejected at the boundary instead of travelling deep into your code.
A name that is not a constant, such as "RETURNED", fails with InvalidFormatException, which lists the accepted values. Names are case-sensitive, so "shipped" fails too, unless you enable MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS. Adding a new status to a public API is a change every client must be ready for.
Fix the error
Make the status readable
Read the error, then pick the line that fixes it.
The status update from the courier is rejected. Fix line 3.
Error
InvalidFormatException: Cannot deserialize value of type `OrderStatus` from String "shipped": not one of the values accepted for Enum class: [PLACED, SHIPPED, DELIVERED]
Next step
Check your understanding
12 quick questions