您可以在货币字段中使用自定义序列化程序。下面是一个MoneyBean的例子。字段数量使用 @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());
}
}
就是这样。大十进制现在以正确的方式打印。我用了一个简单的测试用例来展示它:
@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));
}