java
40 lines · 8 steps
Serializing Money to JSON in Spring
A custom Jackson serializer renders JavaMoney amounts as a clean, currency-aware JSON object and wires itself into Spring.
Explained by
highlit
1import com.fasterxml.jackson.core.JsonGenerator;
2import com.fasterxml.jackson.databind.JsonSerializer;
3import com.fasterxml.jackson.databind.SerializerProvider;
4import com.fasterxml.jackson.databind.module.SimpleModule;
5import org.javamoney.moneta.Money;
6import org.springframework.context.annotation.Bean;
7import org.springframework.context.annotation.Configuration;
8
9import java.io.IOException;
10import java.math.RoundingMode;
11
12public class MoneySerializer extends JsonSerializer<Money> {
13
14 @Override
15 public void serialize(Money value, JsonGenerator gen, SerializerProvider provider) throws IOException {
16 Money rounded = value.with(java.util.Currency.getInstance(value.getCurrency().getCurrencyCode())
17 .getDefaultFractionDigits() >= 0
18 ? org.javamoney.moneta.function.MonetaryOperators.rounding(RoundingMode.HALF_UP)
19 : org.javamoney.moneta.function.MonetaryOperators.rounding());
20
21 gen.writeStartObject();
22 gen.writeStringField("currency", rounded.getCurrency().getCurrencyCode());
23 gen.writeStringField("amount", rounded.getNumberStripped().toPlainString());
24 gen.writeNumberField("minorUnits", rounded.getNumberStripped()
25 .movePointRight(rounded.getCurrency().getDefaultFractionDigits())
26 .longValueExact());
27 gen.writeEndObject();
28 }
29
30 @Configuration
31 public static class MoneyJacksonConfig {
32
33 @Bean
34 public SimpleModule moneyModule() {
35 SimpleModule module = new SimpleModule("MoneyModule");
36 module.addSerializer(Money.class, new MoneySerializer());
37 return module;
38 }
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Custom JsonSerializers give you full control over how domain types appear in JSON.
- 2Rounding money to its currency's fraction digits before output avoids leaking floating-point noise.
- 3Registering a SimpleModule as a Spring bean makes Jackson pick up custom serializers automatically.
Related explainers
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
java
@Component public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler { private final RefreshTokenService refreshTokenService;
Issuing JWT and refresh tokens on login in Spring
authentication
jwt
http-cookies
Intermediate
7 steps
php
<?php namespace App\Services;
Building a valid iCalendar feed in PHP in Laravel
ical
serialization
formatting
Intermediate
8 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
java
@Repository public interface SubscriptionRepository extends JpaRepository<Subscription, Long> { @Modifying(clearAutomatically = true, flushAutomatically = true)
Bulk JPQL updates in a Spring Data repository
jpql
bulk-update
modifying-query
Intermediate
5 steps
java
package com.example.uploads.config; import jakarta.servlet.MultipartConfigElement; import org.springframework.boot.web.servlet.MultipartConfigFactory;
Configuring upload size limits in Spring
file-upload
exception-handling
http-errors
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serializing-money-to-json-in-spring-explained-java-8d64/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.