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,35 @@
|
||||
package com.ankurm.jackson3.part4custom;
|
||||
|
||||
import tools.jackson.core.JsonParser;
|
||||
import tools.jackson.databind.DeserializationContext;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* Post: Custom Serialisers and Mix-ins — https://ankurm.com/jackson-custom-serializer-mixin/
|
||||
* Section: "Writing a Custom Deserialiser"
|
||||
*
|
||||
* Jackson 3 differences from the post's code:
|
||||
* 1. jsonParser.getCodec().readTree(jsonParser) is gone. Use ctxt.readTree(parser).
|
||||
* 2. No `throws IOException` — JacksonException is unchecked.
|
||||
* 3. path() rather than get(), so a missing field yields a MissingNode instead of
|
||||
* a NullPointerException. The post's version NPEs on {"currency":"USD"}.
|
||||
* 4. A bare decimalValue() on a MissingNode THROWS in Jackson 3 (it returned
|
||||
* BigDecimal.ZERO in Jackson 2). Use the defaulting overload.
|
||||
*/
|
||||
public class E02MoneyValueDeserializer extends StdDeserializer<Money> {
|
||||
|
||||
public E02MoneyValueDeserializer() {
|
||||
super(Money.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Money deserialize(JsonParser jsonParser, DeserializationContext ctxt) {
|
||||
JsonNode rootNode = ctxt.readTree(jsonParser);
|
||||
BigDecimal amount = rootNode.path("amount").decimalValue(BigDecimal.ZERO);
|
||||
String currency = rootNode.path("currency").asString("GBP"); // default when absent
|
||||
return new Money(amount, currency);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user