使用Jackson序列化一个Double到2的小数位 [英] Serialize a Double to 2 decimal places using Jackson

查看:2699
本文介绍了使用Jackson序列化一个Double到2的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jackson ,用 Spring MVC 来写出一些简单的对象 JSON 。其中一个对象具有金额属性,类型为 Double 。 (我知道 Double 不应该用作货币金额。但是,这不是我的代码。)



JSON 输出中,我想将金额限制为2位小数。目前显示为:

 金额:459.99999999999994 

我尝试过使用Spring 3的 @NumberFormat 注释,但是没有成功方向。看起来其他人也有问题: MappingJacksonHttpMessageConverter的ObjectMapper在此处将JSON绑定到JavaBean propertiesenter链接描述时不使用ConversionService 。 / p>

另外,我尝试使用 @JsonSerialize 注释和自定义序列化器。

In模型:

  @JsonSerialize(using = CustomDoubleSerializer.class)
public Double getAmount()

序列化器实现:

 公共类CustomDoubleSerializer扩展了JsonSerializer< Double> {
@Override
public void serialize(Double value,JsonGenerator jgen,SerializerProvider provider)抛出IOException,JsonGenerationException {
if(null == value){
//写这个词如果没有可用值,则为'null'
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(输出);
}
}
}

CustomDoubleSerializer 似乎工作。但是,任何人都可以建议任何其他更简单(或更标准)的方法。

解决方案


我知道 Double 不应该用作金额。但是,
这不是我的代码。


确实,它不应该。 BigDecimal 是存储货币金额的更好选择,因为它无损 并且提供更多小数位控制。



因此对于那些可以控制代码的人来说,可以这样使用:

  double amount = 111.222; 
setAmount(new BigDecimal(amount).setScale(2,BigDecimal.ROUND_HALF_UP));

这将序列化为 111.22 。无需自定义序列化程序。


I'm using Jackson, with Spring MVC, to write out some simple objects as JSON. One of the objects, has an amount property, of type Double. (I know that Double should not be used as a monetary amount. However, this is not my code.)

In the JSON output, I'd like to restrict the amount to 2 decimal places. Currently it is shown as:

"amount":459.99999999999994

I've tried using Spring 3's @NumberFormat annotation, but haven't had success in that direction. Looks like others had issues too: MappingJacksonHttpMessageConverter's ObjectMapper does not use ConversionService when binding JSON to JavaBean propertiesenter link description here.

Also, I tried using the @JsonSerialize annotation, with a custom serializer.
In the model:

@JsonSerialize(using = CustomDoubleSerializer.class)
public Double getAmount()

And serializer implementation:

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);
        }
    }
}

The CustomDoubleSerializer "appears" to work. However, can anyone suggest any other simpler (or more standard) way of doing this.

解决方案

I know that Double should not be used as a monetary amount. However, this is not my code.

Indeed, it should not. BigDecimal is a much better choice for storing monetary amounts because it is lossless and provides more control of the decimal places.

So for people who do have control over the code, it can be used like this:

double amount = 111.222;
setAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));

That will serialize as 111.22. No custom serializers needed.

这篇关于使用Jackson序列化一个Double到2的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆