1
0

Part 2: records need no module, annotation or -parameters flag

This commit is contained in:
2026-08-04 17:30:04 +00:00
parent a5c3179cd1
commit f1fca2e339

View File

@@ -0,0 +1,36 @@
package com.ankurm.jackson3.part2modernjava;
import tools.jackson.databind.json.JsonMapper;
/**
* Post: Jackson with Records, Optionals, Sealed Classes
* https://ankurm.com/jackson-java-records-optionals/
* Section: "Jackson with Java Records"
*
* Records need no module, no annotation and no -parameters compiler flag in
* Jackson 3. Check the pom: there is no jackson-module-parameter-names dependency
* and no <compilerArgs>.
*/
public class C01RecordRoundTrip {
/** A concise, immutable data transfer object. */
public record ProductRecord(Long productId, String productName, double unitPrice) { }
public static void main(String[] args) {
JsonMapper mapper = JsonMapper.builder().build();
// Serialise: Record -> JSON. Accessor methods replace getters.
ProductRecord product = new ProductRecord(101L, "Wireless Keyboard", 49.99);
String jsonOutput = mapper.writeValueAsString(product);
System.out.println(jsonOutput);
// Deserialise: JSON -> Record. The canonical constructor is located through
// the RecordComponent reflection API (Java 16+), not through parameter names.
String json = "{\"productId\":101,\"productName\":\"Wireless Keyboard\",\"unitPrice\":49.99}";
ProductRecord restored = mapper.readValue(json, ProductRecord.class);
System.out.println(restored.productName());
// Records also give you equals() for free, so a round-trip is assertable.
System.out.println("round-trip equal: " + product.equals(restored));
}
}