Files
jackson3-by-example/src/main/java/com/ankurm/jackson3/part4custom/E01MoneyValueSerializer.java
T
asmhatre c438afc33b 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.
2026-08-04 23:29:26 +05:30

39 lines
1.5 KiB
Java

package com.ankurm.jackson3.part4custom;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ser.std.StdSerializer;
import java.math.RoundingMode;
/**
* Post: Custom Serialisers and Mix-ins — https://ankurm.com/jackson-custom-serializer-mixin/
* Section: "Writing a Custom Serialiser"
*
* Three Jackson 3 differences from the code in the post:
* 1. Package is tools.jackson.databind.ser.std, not com.fasterxml.jackson...
* 2. The third parameter is SerializationContext, not SerializerProvider.
* 3. There is no `throws IOException` — JacksonException is unchecked in Jackson 3.
*
* (StdSerializer still exists under its old name; only JsonSerializer was renamed,
* to ValueSerializer. StdSerializer extends ValueSerializer.)
*/
public class E01MoneyValueSerializer extends StdSerializer<Money> {
public E01MoneyValueSerializer() {
super(Money.class);
}
@Override
public void serialize(Money moneyValue, JsonGenerator jsonGenerator, SerializationContext ctxt) {
jsonGenerator.writeStartObject();
// Write the amount rounded to 2 decimal places
jsonGenerator.writeNumberProperty("amount",
moneyValue.amount().setScale(2, RoundingMode.HALF_UP));
// Write the ISO currency code in uppercase
jsonGenerator.writeStringProperty("currency",
moneyValue.currencyCode().toUpperCase());
jsonGenerator.writeEndObject();
}
}