Part 2: records need no module, annotation or -parameters flag
This commit is contained in:
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user