Java 到 Jackson JSON 序列化:Money 字段 [英] Java to Jackson JSON serialization: Money fields
问题描述
目前,我使用 Jackson 从基于 Spring 的 Web 应用程序发送 JSON 结果.
Currently, I'm using Jackson to send out JSON results from my Spring-based web application.
我遇到的问题是试图让所有货币字段以 2 位小数输出.我无法使用 setScale(2)
解决这个问题,因为像 25.50 这样的数字被截断为 25.5 等
The problem I'm having is trying to get all money fields to output with 2 decimal places. I wasn't able to solve this problem using setScale(2)
, as numbers like 25.50 are truncated to 25.5 etc
有没有其他人处理过这个问题?我正在考虑使用自定义 Jackson 序列化程序制作 Money 类……您能为字段变量制作自定义序列化程序吗?您可能可以...但即便如此,我如何才能让我的客户序列化程序将该数字添加为带有 2 个小数位的数字?
Has anyone else dealt with this problem? I was thinking about making a Money class with a custom Jackson serializer... can you make a custom serializer for a field variable? You probably can... But even still, how could I get my customer serializer to add the number as a number with 2 decimal places?
推荐答案
您可以在您的资金领域使用自定义序列化程序.这是一个使用 MoneyBean 的示例.字段 amount 使用 @JsonSerialize(using=...) 进行注释.
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());
}
}
就是这样.BigDecimal 现在以正确的方式打印.我使用了一个简单的测试用例来展示它:
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));
}
这篇关于Java 到 Jackson JSON 序列化:Money 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!