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,11 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
public class BankTransferPayment extends PaymentMethod {
|
||||
private String bankAccountIban;
|
||||
private String bankName;
|
||||
|
||||
public String getBankAccountIban() { return bankAccountIban; }
|
||||
public String getBankName() { return bankName; }
|
||||
public void setBankAccountIban(String v) { this.bankAccountIban = v; }
|
||||
public void setBankName(String v) { this.bankName = v; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
public class CreditCardPayment extends PaymentMethod {
|
||||
private String cardNumberLastFour;
|
||||
private String cardNetwork; // "VISA", "MASTERCARD", etc.
|
||||
|
||||
public String getCardNumberLastFour() { return cardNumberLastFour; }
|
||||
public String getCardNetwork() { return cardNetwork; }
|
||||
public void setCardNumberLastFour(String v) { this.cardNumberLastFour = v; }
|
||||
public void setCardNetwork(String v) { this.cardNetwork = v; }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Post: Polymorphic Deserialisation — https://ankurm.com/jackson-polymorphic-deserialization/
|
||||
* Section: "Serialising a Mixed List"
|
||||
*
|
||||
* CORRECTION TO THE POST. The post shows
|
||||
*
|
||||
* mapper.writerWithDefaultPrettyPrinter().writeValueAsString(payments)
|
||||
*
|
||||
* producing JSON that contains "paymentType". It does not. Passing a List to
|
||||
* writeValueAsString gives Jackson only the runtime class (ImmutableCollections.ListN),
|
||||
* which carries no element type, so the polymorphic type serialiser is never engaged
|
||||
* and the discriminator is silently omitted. The resulting JSON then fails to
|
||||
* deserialise — see F02DeserialiseMixedList.
|
||||
*
|
||||
* Two things do work: a typed array, or writerFor(TypeReference).
|
||||
*/
|
||||
public class F01SerialiseMixedList {
|
||||
|
||||
static List<PaymentMethod> samplePayments() {
|
||||
CreditCardPayment card = new CreditCardPayment();
|
||||
card.setPaymentId(1L);
|
||||
card.setAmountDue(99.99);
|
||||
card.setCardNumberLastFour("4242");
|
||||
card.setCardNetwork("VISA");
|
||||
|
||||
BankTransferPayment bank = new BankTransferPayment();
|
||||
bank.setPaymentId(2L);
|
||||
bank.setAmountDue(250.00);
|
||||
bank.setBankAccountIban("GB29NWBK60161331926819");
|
||||
bank.setBankName("National Bank");
|
||||
|
||||
return List.of(card, bank);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
List<PaymentMethod> payments = samplePayments();
|
||||
|
||||
System.out.println("--- 1. single element: discriminator present ---");
|
||||
System.out.println(mapper.writeValueAsString(payments.get(0)));
|
||||
|
||||
System.out.println("--- 2. BROKEN: writeValueAsString(List) drops paymentType ---");
|
||||
System.out.println(mapper.writeValueAsString(payments));
|
||||
|
||||
System.out.println("--- 3. FIX A: writerFor(TypeReference) ---");
|
||||
System.out.println(mapper.writerFor(new TypeReference<List<PaymentMethod>>() { })
|
||||
.withDefaultPrettyPrinter()
|
||||
.writeValueAsString(payments));
|
||||
|
||||
System.out.println("--- 4. FIX B: a typed array carries its component type ---");
|
||||
System.out.println(mapper.writeValueAsString(payments.toArray(new PaymentMethod[0])));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Post: Polymorphic Deserialisation — https://ankurm.com/jackson-polymorphic-deserialization/
|
||||
* Section: "Deserialising a Mixed List"
|
||||
*
|
||||
* Deserialisation is the half that works exactly as the post describes — and it is
|
||||
* also what proves the serialisation defect in F01: feed it the discriminator-less
|
||||
* JSON and it fails outright.
|
||||
*/
|
||||
public class F02DeserialiseMixedList {
|
||||
|
||||
private static final String GOOD_JSON = "["
|
||||
+ "{\"paymentType\":\"credit_card\",\"paymentId\":1,\"amountDue\":99.99,"
|
||||
+ "\"cardNumberLastFour\":\"4242\",\"cardNetwork\":\"VISA\"},"
|
||||
+ "{\"paymentType\":\"bank_transfer\",\"paymentId\":2,\"amountDue\":250.0,"
|
||||
+ "\"bankAccountIban\":\"GB29NWBK60161331926819\",\"bankName\":\"National Bank\"}"
|
||||
+ "]";
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
List<PaymentMethod> payments =
|
||||
mapper.readValue(GOOD_JSON, new TypeReference<List<PaymentMethod>>() { });
|
||||
|
||||
for (PaymentMethod payment : payments) {
|
||||
if (payment instanceof CreditCardPayment cc) {
|
||||
System.out.println("Card ending: " + cc.getCardNumberLastFour());
|
||||
} else if (payment instanceof BankTransferPayment bt) {
|
||||
System.out.println("Bank: " + bt.getBankName());
|
||||
}
|
||||
}
|
||||
|
||||
// Now prove the F01 defect matters: the lossy output cannot be read back.
|
||||
String lossy = mapper.writeValueAsString(F01SerialiseMixedList.samplePayments());
|
||||
try {
|
||||
mapper.readValue(lossy, new TypeReference<List<PaymentMethod>>() { });
|
||||
System.out.println("unreachable");
|
||||
} catch (Exception e) {
|
||||
System.out.println("lossy JSON round-trip -> " + e.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
// Whereas the correctly written output does round-trip.
|
||||
String correct = mapper.writerFor(new TypeReference<List<PaymentMethod>>() { })
|
||||
.writeValueAsString(F01SerialiseMixedList.samplePayments());
|
||||
List<PaymentMethod> again =
|
||||
mapper.readValue(correct, new TypeReference<List<PaymentMethod>>() { });
|
||||
System.out.println("correct JSON round-trip -> " + again.size() + " payments, "
|
||||
+ again.get(0).getClass().getSimpleName() + " first");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Polymorphic Deserialisation — https://ankurm.com/jackson-polymorphic-deserialization/
|
||||
* Section: "@JsonTypeInfo Placement Options"
|
||||
*
|
||||
* The post gives a table of the four include strategies. This runs all four so you
|
||||
* can see the actual wire format instead of trusting the table.
|
||||
*/
|
||||
public class F03IncludeStrategies {
|
||||
|
||||
// ---- As.PROPERTY: discriminator is an ordinary field inside the object ----
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind")
|
||||
@JsonSubTypes(@JsonSubTypes.Type(value = PropCard.class, name = "card"))
|
||||
public interface PropBase { }
|
||||
public record PropCard(double amountDue) implements PropBase { }
|
||||
|
||||
// ---- As.WRAPPER_OBJECT: object wrapped in a single-key envelope ----
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
|
||||
@JsonSubTypes(@JsonSubTypes.Type(value = WrapObjCard.class, name = "card"))
|
||||
public interface WrapObjBase { }
|
||||
public record WrapObjCard(double amountDue) implements WrapObjBase { }
|
||||
|
||||
// ---- As.WRAPPER_ARRAY: two-element [name, object] array ----
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_ARRAY)
|
||||
@JsonSubTypes(@JsonSubTypes.Type(value = WrapArrCard.class, name = "card"))
|
||||
public interface WrapArrBase { }
|
||||
public record WrapArrCard(double amountDue) implements WrapArrBase { }
|
||||
|
||||
// ---- As.EXISTING_PROPERTY: reuses a field the class already declares ----
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY,
|
||||
property = "kind", visible = true)
|
||||
@JsonSubTypes(@JsonSubTypes.Type(value = ExistingCard.class, name = "card"))
|
||||
public interface ExistingBase { String kind(); }
|
||||
public record ExistingCard(String kind, double amountDue) implements ExistingBase { }
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
System.out.println("PROPERTY : " + mapper.writeValueAsString((PropBase) new PropCard(99.0)));
|
||||
System.out.println("WRAPPER_OBJECT : " + mapper.writeValueAsString((WrapObjBase) new WrapObjCard(99.0)));
|
||||
System.out.println("WRAPPER_ARRAY : " + mapper.writeValueAsString((WrapArrBase) new WrapArrCard(99.0)));
|
||||
System.out.println("EXISTING_PROPERTY : " + mapper.writeValueAsString((ExistingBase) new ExistingCard("card", 99.0)));
|
||||
|
||||
// Each form reads back to the correct concrete type.
|
||||
System.out.println("read PROPERTY -> " + mapper.readValue("{\"kind\":\"card\",\"amountDue\":99.0}", PropBase.class));
|
||||
System.out.println("read WRAPPER_OBJECT -> " + mapper.readValue("{\"card\":{\"amountDue\":99.0}}", WrapObjBase.class));
|
||||
System.out.println("read WRAPPER_ARRAY -> " + mapper.readValue("[\"card\",{\"amountDue\":99.0}]", WrapArrBase.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* BEYOND THE POST — what actually happens when the discriminator is wrong.
|
||||
*
|
||||
* The security post asserts that an unregistered type name throws
|
||||
* InvalidTypeIdException. This runs the three failure modes so the exception types
|
||||
* are on the record rather than assumed: unknown name, attacker-supplied class name,
|
||||
* and a missing discriminator.
|
||||
*/
|
||||
public class F04UnknownTypeId {
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
attempt(mapper, "unknown logical name",
|
||||
"{\"paymentType\":\"crypto\",\"paymentId\":9,\"amountDue\":1.0}");
|
||||
|
||||
attempt(mapper, "attacker-supplied class name",
|
||||
"{\"paymentType\":\"com.malicious.Gadget\",\"paymentId\":9,\"amountDue\":1.0}");
|
||||
|
||||
attempt(mapper, "missing discriminator",
|
||||
"{\"paymentId\":9,\"amountDue\":1.0}");
|
||||
}
|
||||
|
||||
private static void attempt(JsonMapper mapper, String label, String json) {
|
||||
try {
|
||||
PaymentMethod result = mapper.readValue(json, PaymentMethod.class);
|
||||
System.out.printf("%-30s -> UNEXPECTEDLY OK: %s%n", label, result);
|
||||
} catch (Exception e) {
|
||||
System.out.printf("%-30s -> %s%n", label, e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.jackson3.part5polymorphic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
|
||||
/**
|
||||
* Post: Polymorphic Deserialisation — https://ankurm.com/jackson-polymorphic-deserialization/
|
||||
* Section: "Setting Up the Hierarchy with @JsonTypeInfo and @JsonSubTypes"
|
||||
*/
|
||||
@JsonTypeInfo(
|
||||
use = JsonTypeInfo.Id.NAME, // use a logical name as the discriminator
|
||||
include = JsonTypeInfo.As.PROPERTY, // embed it as a field in the JSON object
|
||||
property = "paymentType" // the JSON key that carries the type name
|
||||
)
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = CreditCardPayment.class, name = "credit_card"),
|
||||
@JsonSubTypes.Type(value = BankTransferPayment.class, name = "bank_transfer")
|
||||
})
|
||||
public abstract class PaymentMethod {
|
||||
private Long paymentId;
|
||||
private double amountDue;
|
||||
|
||||
public Long getPaymentId() { return paymentId; }
|
||||
public double getAmountDue() { return amountDue; }
|
||||
public void setPaymentId(Long v) { this.paymentId = v; }
|
||||
public void setAmountDue(double v) { this.amountDue = v; }
|
||||
}
|
||||
Reference in New Issue
Block a user