我正在使用 Jackson
和 Spring MVC
,将一些简单的对象写成 JSON
。其中一个对象具有 amount
属性,类型为 Double
。 (我知道 Double
不应该用作货币金额。但是,这不是我的代码。)
在 JSON
输出中,我想将数量限制为小数点后 2 位。目前显示为:
"amount":459.99999999999994
我尝试过使用 Spring 3 的 @NumberFormat
注释,但在这个方向上没有成功。看起来其他人也有问题:MappingJacksonHttpMessageConverter's ObjectMapper does not use ConversionService when binding JSON to JavaBean propertiesenter link description here .
另外,我尝试使用带有自定义序列化程序的 @JsonSerialize
注释。
在模型中:
@JsonSerialize(using = CustomDoubleSerializer.class)
public Double getAmount()
和序列化器实现:
public class CustomDoubleSerializer extends JsonSerializer<Double> {
@Override
public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
if (null == value) {
//write the word 'null' if there's no value available
jgen.writeNull();
} else {
final String pattern = ".##";
//final String pattern = "###,###,##0.00";
final DecimalFormat myFormatter = new DecimalFormat(pattern);
final String output = myFormatter.format(value);
jgen.writeNumber(output);
}
}
}
CustomDoubleSerializer
“似乎”可以工作。但是,任何人都可以提出任何其他更简单(或更标准)的方法吗?
最佳答案
I know that
Double
should not be used as a monetary amount. However, this is not my code.
确实不应该。 BigDecimal
是存储货币金额的更好选择,因为它无损 并且提供了对小数位的更多控制。
所以对于对代码有控制权的人,可以这样使用:
double amount = 111.222;
setAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
这将序列化为 111.22
。无需自定义序列化程序。
关于java - 使用 Jackson 将 Double 序列化到小数点后 2 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520781/