37 runnable examples covering the eight feature posts on ankurm.com, verified against Jackson 3.2.1 on Temurin 21.0.5. Every output committed under docs/ was produced by run-all.sh. Also documents 11 places where the published snippets do not compile or do not behave as printed against a real Jackson 3 build - most notably that writeValueAsString(List<Base>) silently drops the polymorphic type discriminator, so the post's serialised output cannot be read back.
50 lines
2.1 KiB
Java
50 lines
2.1 KiB
Java
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.
|
|
}
|
|
}
|