简体   繁体   中英

How to display BigDecimal number with trailing zero in a JSON (not as string)?

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

If you want to keep the JSON holding a numeric value, you don't have the choice, a numeric isn't impacted by the traling "0" in a decimal part, so they won't be used. Simply because :

2.3 = 2.30
2.3 = 2.300000

The zeros are simply ignored. If you really need to get a value like 2.30, you have two choices,

  1. use a String to hold the formatted number in the JSON
  2. format the value on the client side.

Both solution will used the same logic :

String.format("%.2f", 2.3); //String: 2.30

The difference is the moment you format the value.

Note:

Since you have a "version" field, I would use a String since a version is represented by numeric value separated by . . See the maven repo of Jackson :

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.4</version>
</dependency>

2.9.4 is not a number.

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM