Part 4: custom deserialiser using ctxt.readTree and null-safe path()
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