• Stars
    star
    240
  • Rank 168,229 (Top 4 %)
  • Language
    Java
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extension module to properly support datatypes of javax.money

Jackson Datatype Money

Stability: Sustained Build Status Coverage Status Code Quality Javadoc Release Maven Central License

Jackson Datatype Money is a Jackson module to support JSON serialization and deserialization of JavaMoney data types. It fills a niche, in that it integrates JavaMoney and Jackson so that they work seamlessly together, without requiring additional developer effort. In doing so, it aims to perform a small but repetitive task β€” once and for all.

This library reflects our API preferences for representing monetary amounts in JSON:

{
  "amount": 29.95,
  "currency": "EUR"
}

Features

  • enables you to express monetary amounts in JSON
  • can be used in a REST APIs
  • customized field names
  • localization of formatted monetary amounts
  • allows you to implement RESTful API endpoints that format monetary amounts based on the Accept-Language header
  • is unique and flexible

Dependencies

  • Java 8 or higher
  • Any build tool using Maven Central, or direct download
  • Jackson
  • JavaMoney

Installation

Add the following dependency to your project:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>jackson-datatype-money</artifactId>
    <version>${jackson-datatype-money.version}</version>
</dependency>

For ultimate flexibility, this module is compatible with the official version as well as the backport of JavaMoney. The actual version will be selected by a profile based on the current JDK version.

Configuration

Register the module with your ObjectMapper:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule());

Alternatively, you can use the SPI capabilities:

ObjectMapper mapper = new ObjectMapper()
    .findAndRegisterModules();

Serialization

For serialization this module currently supports javax.money.MonetaryAmount and will, by default, serialize it as:

{
  "amount": 99.95,
  "currency": "EUR"
}

To serialize number as a JSON string, you have to configure the quoted decimal number value serializer:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule().withQuotedDecimalNumbers());
{
  "amount": "99.95",
  "currency": "EUR"
}

Formatting

A special feature for serializing monetary amounts is formatting, which is disabled by default. To enable it, you have to either enable default formatting:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule().withDefaultFormatting());

... or pass in a MonetaryAmountFormatFactory implementation to the MoneyModule:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule()
        .withFormatting(new CustomMonetaryAmountFormatFactory()));

The default formatting delegates directly to MonetaryFormats.getAmountFormat(Locale, String...).

Formatting only affects the serialization and can be customized based on the current locale, as defined by the SerializationConfig. This allows to implement RESTful API endpoints that format monetary amounts based on the Accept-Language header.

The first example serializes a monetary amount using the de_DE locale:

ObjectWriter writer = mapper.writer().with(Locale.GERMANY);
writer.writeValueAsString(Money.of(29.95, "EUR"));
{
  "amount": 29.95,
  "currency": "EUR",
  "formatted": "29,95 EUR"
}

The following example uses en_US:

ObjectWriter writer = mapper.writer().with(Locale.US);
writer.writeValueAsString(Money.of(29.95, "USD"));
{
  "amount": 29.95,
  "currency": "USD",
  "formatted": "USD29.95"
}

More sophisticated formatting rules can be supported by implementing MonetaryAmountFormatFactory directly.

Deserialization

This module will use org.javamoney.moneta.Money as an implementation for javax.money.MonetaryAmount by default when deserializing money values. If you need a different implementation, you can pass a different MonetaryAmountFactory to the MoneyModule:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule()
        .withMonetaryAmount(new CustomMonetaryAmountFactory()));

You can also pass in a method reference:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule()
        .withMonetaryAmount(FastMoney::of));

Jackson Datatype Money comes with support for all MonetaryAmount implementations from Moneta, the reference implementation of JavaMoney:

MonetaryAmount Implementation Factory
org.javamoney.moneta.FastMoney new MoneyModule().withFastMoney()
org.javamoney.moneta.Money new MoneyModule().withMoney()
org.javamoney.moneta.RoundedMoney new MoneyModule().withRoundedMoney()

Module supports deserialization of amount number from JSON number as well as from JSON string without any special configuration required.

Custom Field Names

As you have seen in the previous examples the MoneyModule uses the field names amount, currency and formatted by default. Those names can be overridden if desired:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new MoneyModule()
        .withAmountFieldName("value")
        .withCurrencyFieldName("unit")
        .withFormattedFieldName("pretty"));

Usage

After registering and configuring the module you're now free to directly use MonetaryAmount in your data types:

import javax.money.MonetaryAmount;

public class Product {
    private String sku;
    private MonetaryAmount price;
    ...
}

Getting help

If you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.

Getting involved

To contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. Please note that we aim to keep this project straightforward and focused. We are not looking to add lots of features; we just want it to keep doing what it does, as well and as powerfully as possible. For more details check the contribution guidelines.

More Repositories

1

patroni

A template for PostgreSQL High Availability with Etcd, Consul, ZooKeeper, or Kubernetes
Python
6,267
star
2

postgres-operator

Postgres operator creates and manages PostgreSQL clusters running in Kubernetes
Go
3,686
star
3

skipper

An HTTP router and reverse proxy for service composition, including use cases like Kubernetes Ingress
Go
3,088
star
4

restful-api-guidelines

A model set of guidelines for RESTful APIs and Events, created by Zalando
CSS
2,605
star
5

zalenium

A flexible and scalable container based Selenium Grid with video recording, live preview, basic auth & dashboard.
Java
2,385
star
6

SwiftMonkey

A framework for doing randomised UI testing of iOS apps
Swift
1,947
star
7

logbook

An extensible Java library for HTTP request and response logging
Java
1,788
star
8

tailor

A streaming layout service for front-end microservices
JavaScript
1,728
star
9

tech-radar

Visualizing our technology choices
1,581
star
10

spilo

Highly available elephant herd: HA PostgreSQL cluster using Docker
Python
1,225
star
11

intellij-swagger

A plugin to help you easily edit Swagger and OpenAPI specification files inside IntelliJ IDEA
Java
1,172
star
12

problem-spring-web

A library for handling Problems in Spring Web MVC
Java
1,031
star
13

nakadi

A distributed event bus that implements a RESTful API abstraction on top of Kafka-like queues
Java
928
star
14

zally

A minimalistic, simple-to-use API linter
Kotlin
903
star
15

problem

A Java library that implements application/problem+json
Java
869
star
16

zalando-howto-open-source

Open Source guidance from Zalando, Europe's largest online fashion platform
799
star
17

go-keyring

Cross-platform keyring interface for Go
Go
689
star
18

gin-oauth2

Middleware for Gin Framework users who also want to use OAuth2
Go
579
star
19

zappr

An agent that enforces guidelines for your GitHub repositories
JavaScript
542
star
20

pg_view

Get a detailed, real-time view of your PostgreSQL database and system metrics
Python
494
star
21

engineering-principles

Our guidelines for building new applications and managing legacy systems
376
star
22

gulp-check-unused-css

A build tool for checking your HTML templates for unused CSS classes
CSS
359
star
23

zmon

Real-time monitoring of critical metrics & KPIs via elegant dashboards, Grafana3 visualizations & more
Shell
355
star
24

expan

Open-source Python library for statistical analysis of randomised control trials (A/B tests)
Python
325
star
25

PGObserver

A battle-tested, flexible & comprehensive monitoring solution for your PostgreSQL databases
Python
316
star
26

riptide

Client-side response routing for Spring
Java
292
star
27

grafter

Grafter is a library to configure and wire Scala applications
Scala
240
star
28

opentracing-toolbox

Best-of-breed OpenTracing utilities, instrumentations and extensions
Java
180
star
29

elm-street-404

A fun WebGL game built with Elm
Elm
176
star
30

tokens

Java library for conveniently verifying and storing OAuth 2.0 service access tokens
Java
169
star
31

innkeeper

Simple route management API for Skipper
Scala
166
star
32

public-presentations

List of public talks by Zalando Tech: meetup presentations, recorded conference talks, slides
165
star
33

python-nsenter

Enter kernel namespaces from Python
Python
139
star
34

faux-pas

A library that simplifies error handling for Functional Programming in Java
Java
132
star
35

dress-code

The official style guide and framework for all Zalando Brand Solutions products
CSS
129
star
36

beard

A lightweight, logicless templating engine, written in Scala and inspired by Mustache
Scala
121
star
37

friboo

Utility library for writing microservices in Clojure, with support for Swagger and OAuth
Clojure
117
star
38

spring-cloud-config-aws-kms

Spring Cloud Config add-on that provides encryption via AWS KMS
Java
99
star
39

zalando.github.io

Open Source Documentation and guidelines for Zalando developers
HTML
86
star
40

failsafe-actuator

Endpoint library for the failsafe framework
Java
52
star
41

package-build

A toolset for building system packages using Docker and fpm-cookery
Ruby
35
star
42

ghe-backup

Github Enterprise backup at ZalandoTech (Kubernetes, AWS, Docker)
Shell
30
star
43

rds-health

discover anomalies, performance issues and optimization within AWS RDS
Go
26
star
44

backstage-plugin-api-linter

API Linter is a quality assurance tool that checks the compliance of API's specifications to Zalando's API rules.
TypeScript
12
star
45

.github

Standard github health files
1
star