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

前端 未结 2 1204
盖世英雄少女心
盖世英雄少女心 2021-01-14 18:21

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 trail

2条回答
  •  忘掉有多难
    2021-01-14 18:44

    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 {
          @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;
    

提交回复
热议问题