Use @JsonSerialize to handle BigDecimal suffix uniformly 0

Posted May 26, 20202 min read

1. Question

In the project, the oracle database needs to be converted to mysql, and the table field in Oracle is defined as the number(36, 16) type tool, which is automatically converted to mysql decimal(36, 16). In the Oracle database, the number(36, 16) type field, using the BigDecimal type to map the field, you can normally get the value without the suffix 0. MySQL database is stored as the corresponding field of decimal(36,16), use BigDecimal to map, you will get the value with 0 suffix. For example, in Oracle, the actual precision is a 16-bit value of 0.000345344. If you use BigDecimal to receive it, you will get 0.000345344, and mysql will get a value of 0.00034533440000000. In this way, there will be a problem when it is returned to the front end.

2. Solution

  • According to business requirements, modify the accuracy of each field under the mysql database. Then manually de-suffix the BigDecimal field in the code.

  • In the json format of the vo layer, remove the 0 suffix.(This scheme is not recommended, but if you want to modify it quickly, you can take it)

        package com.xiayu.config;
    
        import com.fasterxml.jackson.core.JsonGenerator;
        import com.fasterxml.jackson.databind.JsonSerializer;
        import com.fasterxml.jackson.databind.SerializerProvider;
    
        import java.io.IOException;
        import java.math.BigDecimal;
        import java.util.Objects;
    
        public class CustomerBigDecimalSerialize extends JsonSerializer <BigDecimal> {
            @Override
            public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if(Objects.nonNull(value)) {
                    gen.writeNumber(value.stripTrailingZeros());
                    //Remove the 0 suffix, if you want to keep the precision uniformly, you can also use similar processing
                } else {//If it is null, write null
                    gen.writeNull();
                }
            }
        }
    
        //Add @JsonSerialize annotation to the field in the vo field
        @JsonSerialize(using = CustomerBigDecimalSerialize.class)
        private BigDecimal totalExchangeBtc; //The total amount of btc redeemed by usdt deducting electricity bills
        @JsonSerialize(using = CustomerBigDecimalSerialize.class)
        private BigDecimal perTotalExchangeBtc; //The total amount of btc exchanged corresponds to each btc
        @JsonSerialize(using = CustomerBigDecimalSerialize.class)
        private BigDecimal exchangeUsdtPrice; //usdt price at the time of exchange