diff --git a/src/main/java/com/ankurm/jackson3/part4custom/E01MoneyValueSerializer.java b/src/main/java/com/ankurm/jackson3/part4custom/E01MoneyValueSerializer.java new file mode 100644 index 0000000..61f43ea --- /dev/null +++ b/src/main/java/com/ankurm/jackson3/part4custom/E01MoneyValueSerializer.java @@ -0,0 +1,38 @@ +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 { + + 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(); + } +}