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,44 @@
|
||||
package com.ankurm.jackson3.part3annotations;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||
* Sections: "@JsonProperty" and "@JsonIgnore"
|
||||
*
|
||||
* Every @Json* annotation is imported from com.fasterxml.jackson.annotation, even
|
||||
* on Jackson 3. jackson-annotations deliberately keeps the old group ID and package
|
||||
* so one copy can be shared by Jackson 2 and Jackson 3 code on the same classpath.
|
||||
*/
|
||||
public class D01RenameAndIgnore {
|
||||
|
||||
public record OrderSummary(
|
||||
@JsonProperty("order_id") Long orderId,
|
||||
@JsonProperty("customer_name") String customerName) { }
|
||||
|
||||
public record UserAccount(
|
||||
String username,
|
||||
@JsonIgnore String passwordHash) { }
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
System.out.println("rename : "
|
||||
+ mapper.writeValueAsString(new OrderSummary(1001L, "Alice")));
|
||||
|
||||
// Deserialisation honours the renamed key in both directions.
|
||||
OrderSummary back = mapper.readValue(
|
||||
"{\"order_id\":1001,\"customer_name\":\"Alice\"}", OrderSummary.class);
|
||||
System.out.println("read back : " + back);
|
||||
|
||||
System.out.println("ignore : "
|
||||
+ mapper.writeValueAsString(new UserAccount("alice", "$2a$10$secret")));
|
||||
|
||||
// @JsonIgnore is bidirectional: the field is not read from JSON either.
|
||||
UserAccount ignored = mapper.readValue(
|
||||
"{\"username\":\"alice\",\"passwordHash\":\"injected\"}", UserAccount.class);
|
||||
System.out.println("read back : passwordHash=" + ignored.passwordHash());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.jackson3.part3annotations;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||
* Sections: "@JsonInclude" and "@JsonFormat"
|
||||
*
|
||||
* One correction to the post: it says "Without @JsonFormat, Jackson writes LocalDate
|
||||
* as a numeric array by default." That was true in Jackson 2. In Jackson 3, java.time
|
||||
* support is built in and ISO-8601 is the default — the annotation is only needed for
|
||||
* a NON-standard pattern. The `defaultDate` field below proves it.
|
||||
*/
|
||||
public class D02InclusionAndFormat {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record ProductDetails(String productName, String productDescription, Double discountRate) { }
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
public record CompactProduct(String productName, String notes, List<String> tags) { }
|
||||
|
||||
public record InvoiceRecord(
|
||||
Long invoiceId,
|
||||
LocalDate defaultDate, // no annotation
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
|
||||
LocalDate ukStyleDate, // custom pattern
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING)
|
||||
double totalAmount) { } // number as string
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
System.out.println("NON_NULL : "
|
||||
+ mapper.writeValueAsString(new ProductDetails("Keyboard", null, null)));
|
||||
System.out.println("NON_EMPTY : "
|
||||
+ mapper.writeValueAsString(new CompactProduct("Keyboard", "", List.of())));
|
||||
|
||||
System.out.println("formats : " + mapper.writeValueAsString(new InvoiceRecord(
|
||||
500L, LocalDate.of(2026, 4, 9), LocalDate.of(2026, 4, 9), 199.99)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.jackson3.part3annotations;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||
* Sections: "@JsonAlias" and "@JsonIgnoreProperties"
|
||||
*
|
||||
* Correction to the post: it frames @JsonIgnoreProperties(ignoreUnknown = true) as the
|
||||
* per-class alternative to configuring FAIL_ON_UNKNOWN_PROPERTIES globally. In Jackson 3
|
||||
* that feature is already DISABLED by default, so unknown fields are tolerated with no
|
||||
* annotation at all. The annotation now matters mainly when you have deliberately turned
|
||||
* strictness back ON — which is what the `strict` mapper below does.
|
||||
*/
|
||||
public class D03AliasAndUnknownFields {
|
||||
|
||||
public record SearchQuery(
|
||||
@JsonAlias({ "q", "query", "search_term" }) String searchKeyword) { }
|
||||
|
||||
public record LenientResponse(String status, String message) { }
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record OptedOutResponse(String status, String message) { }
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
for (String json : new String[] {
|
||||
"{\"q\":\"jackson\"}", "{\"query\":\"jackson\"}", "{\"search_term\":\"jackson\"}" }) {
|
||||
System.out.println("alias " + String.format("%-24s", json)
|
||||
+ " -> " + mapper.readValue(json, SearchQuery.class).searchKeyword());
|
||||
}
|
||||
|
||||
String extra = "{\"status\":\"OK\",\"message\":\"done\",\"undocumentedField\":42}";
|
||||
|
||||
// Default Jackson 3 mapper: unknown fields are already ignored.
|
||||
System.out.println("default mapper : " + mapper.readValue(extra, LenientResponse.class));
|
||||
|
||||
// A mapper with strictness deliberately re-enabled.
|
||||
JsonMapper strict = JsonMapper.builder()
|
||||
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.build();
|
||||
try {
|
||||
strict.readValue(extra, LenientResponse.class);
|
||||
System.out.println("strict mapper : unreachable");
|
||||
} catch (Exception e) {
|
||||
System.out.println("strict mapper : " + e.getClass().getSimpleName() + " (as expected)");
|
||||
}
|
||||
// ...but the annotation opts this one class back out of the strictness.
|
||||
System.out.println("strict + anno : " + strict.readValue(extra, OptedOutResponse.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.jackson3.part3annotations;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||
* Sections: "@JsonCreator", plus @JsonUnwrapped which the post's table lists but
|
||||
* never demonstrates. @JsonAnyGetter/@JsonAnySetter are beyond the post entirely.
|
||||
*/
|
||||
public class D04CreatorsAndUnwrapping {
|
||||
|
||||
/** Immutable class with no setters: the creator tells Jackson how to build it. */
|
||||
public static class ImmutablePoint {
|
||||
private final double xCoordinate;
|
||||
private final double yCoordinate;
|
||||
|
||||
@JsonCreator
|
||||
public ImmutablePoint(@JsonProperty("x") double xCoordinate,
|
||||
@JsonProperty("y") double yCoordinate) {
|
||||
this.xCoordinate = xCoordinate;
|
||||
this.yCoordinate = yCoordinate;
|
||||
}
|
||||
@JsonProperty("x") public double getXCoordinate() { return xCoordinate; }
|
||||
@JsonProperty("y") public double getYCoordinate() { return yCoordinate; }
|
||||
@Override public String toString() {
|
||||
return "ImmutablePoint(x=" + xCoordinate + ", y=" + yCoordinate + ")";
|
||||
}
|
||||
}
|
||||
|
||||
public record Address(String street, String city) { }
|
||||
|
||||
/** @JsonUnwrapped flattens the nested object into the parent's JSON object. */
|
||||
public static class Customer {
|
||||
public String customerName;
|
||||
@JsonUnwrapped public Address address;
|
||||
public Customer() { }
|
||||
public Customer(String n, Address a) { customerName = n; address = a; }
|
||||
}
|
||||
|
||||
/** Any unmapped properties land in a Map instead of being dropped. */
|
||||
public static class FlexiblePayload {
|
||||
public String knownField;
|
||||
private final Map<String, Object> extras = new LinkedHashMap<>();
|
||||
@JsonAnyGetter public Map<String, Object> extras() { return extras; }
|
||||
@JsonAnySetter public void put(String k, Object v) { extras.put(k, v); }
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
ImmutablePoint point = mapper.readValue("{\"x\":3.5,\"y\":7.2}", ImmutablePoint.class);
|
||||
System.out.println("creator : " + point);
|
||||
System.out.println("round-trip: " + mapper.writeValueAsString(point));
|
||||
|
||||
System.out.println("unwrapped : " + mapper.writeValueAsString(
|
||||
new Customer("Alice", new Address("123 Main St", "Springfield"))));
|
||||
|
||||
FlexiblePayload flexible = mapper.readValue(
|
||||
"{\"knownField\":\"a\",\"surprise\":1,\"another\":[true,false]}", FlexiblePayload.class);
|
||||
System.out.println("any-setter: " + flexible.extras());
|
||||
System.out.println("any-getter: " + mapper.writeValueAsString(flexible));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user