From 52503ad26ec22648cc19d71c353ea33ffd7f3361 Mon Sep 17 00:00:00 2001 From: asmhatre Date: Tue, 4 Aug 2026 17:28:58 +0000 Subject: [PATCH] Part 0: first serialise/deserialise round-trip --- .../part0setup/A01FirstRoundTrip.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/com/ankurm/jackson3/part0setup/A01FirstRoundTrip.java diff --git a/src/main/java/com/ankurm/jackson3/part0setup/A01FirstRoundTrip.java b/src/main/java/com/ankurm/jackson3/part0setup/A01FirstRoundTrip.java new file mode 100644 index 0000000..4c03582 --- /dev/null +++ b/src/main/java/com/ankurm/jackson3/part0setup/A01FirstRoundTrip.java @@ -0,0 +1,49 @@ +package com.ankurm.jackson3.part0setup; + +import tools.jackson.databind.json.JsonMapper; + +/** + * Post: Jackson 101 — https://ankurm.com/jackson-java-tutorial/ + * Section: "Your First Serialise/Deserialise Example" + * + * The simplest possible Jackson 3 round-trip: a POJO out to JSON and back. + */ +public class A01FirstRoundTrip { + + /** A plain POJO with getters and setters — the classic Jackson shape. */ + public static class ProductSummary { + private Long productId; + private String productName; + private double listPrice; + + public ProductSummary() { } // needed for deserialisation + public ProductSummary(Long id, String name, double price) { + this.productId = id; this.productName = name; this.listPrice = price; + } + public Long getProductId() { return productId; } + public String getProductName() { return productName; } + public double getListPrice() { return listPrice; } + public void setProductId(Long v) { this.productId = v; } + public void setProductName(String v) { this.productName = v; } + public void setListPrice(double v) { this.listPrice = v; } + } + + public static void main(String[] args) { + // Jackson 3: JsonMapper.builder().build() replaces `new ObjectMapper()`. + // The result is IMMUTABLE — you cannot reconfigure it afterwards. + JsonMapper mapper = JsonMapper.builder().build(); + + // Serialise: Java object -> JSON string + ProductSummary product = new ProductSummary(1L, "Mechanical Keyboard", 79.99); + String jsonOutput = mapper.writeValueAsString(product); + System.out.println(jsonOutput); + + // Deserialise: JSON string -> Java object + ProductSummary restored = mapper.readValue(jsonOutput, ProductSummary.class); + System.out.println(restored.getProductName()); + + // Note: no `throws` clause anywhere in this method. In Jackson 3 the + // exception hierarchy is rooted at JacksonException extends RuntimeException, + // so serialisation failures are UNCHECKED. See beyond/Y01UncheckedExceptions. + } +}