Jackson 3 series companion code
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.
This commit is contained in:
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ankurm.jackson3.part0setup;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* Post: Jackson 101 — https://ankurm.com/jackson-java-tutorial/
|
||||
* Section: "The ObjectMapper Lifecycle — The One Rule That Matters Most"
|
||||
*
|
||||
* Build the mapper ONCE at startup and share it. In Jackson 3 this is enforced
|
||||
* by the API rather than by convention: the built mapper has no setters at all.
|
||||
*/
|
||||
public class A02SharedMapperConfiguration {
|
||||
|
||||
public record Invoice(Long invoiceId, String customerName, LocalDate issuedOn, String note) { }
|
||||
|
||||
/**
|
||||
* The Jackson 3 equivalent of the classic Spring @Bean ObjectMapper.
|
||||
*
|
||||
* Three of the four settings people habitually copy from Jackson 2 tutorials
|
||||
* are unnecessary or wrong in Jackson 3 — the comments say which and why.
|
||||
*/
|
||||
static JsonMapper buildSharedMapper() {
|
||||
return JsonMapper.builder()
|
||||
// NOT NEEDED: FAIL_ON_UNKNOWN_PROPERTIES already defaults to false in
|
||||
// Jackson 3. Listed here only because it is the single most-copied line
|
||||
// from Jackson 2 configuration; deleting it changes nothing.
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
|
||||
// NOT NEEDED: java.time support is built into jackson-databind 3.x and
|
||||
// dates already serialise as ISO-8601 strings. There is no
|
||||
// SerializationFeature.WRITE_DATES_AS_TIMESTAMPS in Jackson 3 — the flag
|
||||
// moved to tools.jackson.databind.cfg.DateTimeFeature and is off by
|
||||
// default. See beyond/Y03DateTimeDefaults for proof.
|
||||
|
||||
// Skip null fields. Jackson 2's setSerializationInclusion(...) and the
|
||||
// builder's serializationInclusion(...) do NOT exist in Jackson 3.
|
||||
// The real API is changeDefaultPropertyInclusion.
|
||||
.changeDefaultPropertyInclusion(
|
||||
incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = buildSharedMapper();
|
||||
|
||||
Invoice invoice = new Invoice(500L, "Alice", LocalDate.of(2026, 4, 9), null);
|
||||
System.out.println("configured : " + mapper.writeValueAsString(invoice));
|
||||
|
||||
JsonMapper plain = JsonMapper.builder().build();
|
||||
System.out.println("defaults : " + plain.writeValueAsString(invoice));
|
||||
|
||||
// Proof that the mapper is immutable: ObjectMapper in Jackson 3 exposes no
|
||||
// set*() mutators at all, so there is no way to reconfigure a shared instance.
|
||||
long setterCount = java.util.Arrays.stream(
|
||||
tools.jackson.databind.ObjectMapper.class.getMethods())
|
||||
.filter(m -> m.getName().startsWith("set"))
|
||||
.count();
|
||||
System.out.println("ObjectMapper set*() methods in Jackson 3: " + setterCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ankurm.jackson3.part0setup;
|
||||
|
||||
import tools.jackson.core.JsonParser;
|
||||
import tools.jackson.core.JsonToken;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson 101 — https://ankurm.com/jackson-java-tutorial/
|
||||
* Section: "Jackson's Three Processing Models"
|
||||
*
|
||||
* The same payload read three ways, so the trade-off is concrete rather than a table.
|
||||
*/
|
||||
public class A03ThreeProcessingModels {
|
||||
|
||||
public record Order(Long orderId, String status) { }
|
||||
|
||||
private static final String JSON = "{\"orderId\":1001,\"status\":\"SHIPPED\"}";
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
// 1. DATA BINDING — the right answer roughly 95% of the time.
|
||||
Order bound = mapper.readValue(JSON, Order.class);
|
||||
System.out.println("1. data binding : " + bound);
|
||||
|
||||
// 2. TREE MODEL — schema not known at compile time; navigate a JsonNode.
|
||||
JsonNode tree = mapper.readTree(JSON);
|
||||
System.out.println("2. tree model : orderId=" + tree.path("orderId").asInt()
|
||||
+ " status=" + tree.path("status").asString());
|
||||
|
||||
// 3. STREAMING — token by token, constant memory, no document ever built.
|
||||
StringBuilder streamed = new StringBuilder();
|
||||
try (JsonParser parser = mapper.createParser(JSON)) {
|
||||
while (parser.nextToken() != null) {
|
||||
if (parser.currentToken() == JsonToken.PROPERTY_NAME) {
|
||||
String field = parser.currentName();
|
||||
parser.nextToken(); // advance to the value
|
||||
streamed.append(field).append('=').append(parser.getString()).append(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("3. streaming : " + streamed.toString().trim());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user