Java to Jackson JSON serialization: Money fields
You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).
public class MoneyBean {
//...
@JsonProperty("amountOfMoney")
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal amount;
//getters/setters...
}
public class MoneySerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
// put your desired money style here
jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
}
}
That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:
@Test
public void jsonSerializationTest() throws Exception {
MoneyBean m = new MoneyBean();
m.setAmount(new BigDecimal("20.3"));
ObjectMapper mapper = new ObjectMapper();
assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
You can use @JsonFormat
annotation with shape
as STRING
on your BigDecimal
variables. Refer below:
import com.fasterxml.jackson.annotation.JsonFormat;
class YourObjectClass {
@JsonFormat(shape=JsonFormat.Shape.STRING)
private BigDecimal yourVariable;
}