java - 使用 Jackson 将 Double 序列化到小数点后 2 位

标签 java jackson

我正在使用 JacksonSpring 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/

相关文章:

java - IntelliJ 和 Eclipse : debug Java application started by Maven exec:exec

scala - sbt 中的 Jackson 版本 : 2. 7.1 不兼容?

java - Junit 测试 - Jackson toString 中的 Eclemma 覆盖率

java - @jsonview of jackson 不使用 jax-rs

java - 使用带有 ScalaObjectMapper 的 Jackson 模块在 Spark 1.4.0 上运行作业时出错

java - 将 ArrayList 添加到 ArrayList 的 ArrayList 时遇到问题

java - 如何在 Java 中使用 HtmlUnit?

java - Intellij Idea中如何获取JavaDocs中某个类的方法摘要

java - Linux 服务器上的 Recaptcha 连接超时

java - 当我尝试在 Spring Controller 的方法中将 json 字符串映射到 java 域类时出现 MethodArgumentConversionNotSupportedException