如何在JSON中显示带尾随零的BigDecimal数字(而不是字符串)? [英] How to display BigDecimal number with trailing zero in a JSON (not as string)?

查看:467
本文介绍了如何在JSON中显示带尾随零的BigDecimal数字(而不是字符串)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表示形式响应中,我有一个BigDecimal类型的字段. 它的值为2.30,但json响应显示为2.3 有没有办法显示尾随零而不显示为字符串? 顺便说一句-我正在使用杰克逊图书馆.

In my representation response I have one field which is of BigDecimal type. Its value is 2.30 but the json response display it as 2.3 Is there any way to show also the trailing zero , without displaying it as a string ? BTW - I'm using Jackson library.

{
  "version" : 2.3 (needs to be 2.30)
}

推荐答案

正如其他人指出的那样,在这种情况下,您确实应该传递字符串以保留格式,因为JSON中的数字类型旨在作为纯值.

As others have pointed out, you should really be passing a string in this case to preserve the formatting, since number types in JSON are intended to be pure values.

但是,如果您确实需要执行此操作(在Jackson生成的JSON中的数字类型上输出尾随零),这就是您的操作方式:

However, if you really need to do this (output trailing zero's on a number type in JSON generated by Jackson), this is how you do it:

创建一个自定义序列化器类,如下所示:

Create a custom serializer class like so:

final class PaddedSerializer extends JsonSerializer<BigDecimal> {
      @Override
      public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
          jgen.writeRawValue(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
      }
    }

然后在绑定类中与所讨论的值相对应的变量上,放置@JsonSerialize批注,以告知它仅在该变量上使用自定义序列化器类:

Then on the variable in your binding class that corresponds to the value in question, place the @JsonSerialize annotation to tell it to use your custom serializer class on just that variable:

@JsonProperty(required = true)
@JsonSerialize(using = PaddedSerializer.class)
protected BigDecimal version;

这篇关于如何在JSON中显示带尾随零的BigDecimal数字(而不是字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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