I am using Jackson in the development of Web API using SpringBoot, but I faced a problem when returning a BigDecimal type value as a response.
That is, it is displayed with consecutive 0s after the decimal point remaining.
For example, assuming that the value "99.9" is registered in the column of numeric type (10, 5) of PostgresSQL, if you get this value and return it in JSON, if you handle it as BigDecimal type and return it, it will be displayed as "99.90000". I will.
This time I solved this phenomenon, so I wrote an article.
First, create a serializer for the BigDecimal type like BigDecimalSerializer.java below. At the time of creation, it is necessary to inherit the StdSerializer
class and specify the target class for manipulating the value in the generics.
BigDecimalSerializer.java
public class BigDecimalSerializer extends StdSerializer<BigDecimal> {
public BigDecimalSerializer() {
this(null);
}
public BigDecimalSerializer(Class<BigDecimal> c) {
super(c);
}
@Override
public void serialize(BigDecimal bigDecimal, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeNumber(new BigDecimal(bigDecimal.stripTrailingZeros().toPlainString()));
}
}
By using the writeNumber
method of the JsonGenerator
class in the serialize
method, you can specify what kind of value to convert to the BigDecimal type value.
This time, I used the stripTrailingZeros
method of the BigDecimal
class to remove the 0s after the decimal point.
However, this method also seems to be in the Official Documentation For example, if you use it for 600.0, the result will be 6E2 and index marking.
Therefore, by using the toPlainString
method of the BigDecimal
class, we made it a non-exponential notation format.
After that, if you add the JsonSerialize
annotation using the BigDecimalSerializer
class created earlier to the field of the class to be returned as a response, it will be displayed with 0s after the decimal point removed.
CalculationResult.java
public class CalculationResult {
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal value;
}
You can create your own serializer by creating a class that inherits from the StdSerializer
class and writing the conversion logic in the serialize
method.
You can customize the value to be returned by adding the JsonSerialize
annotation to the field of the class to be returned as a response and specifying the created serializer.
I hope this article helps someone.
Until the end Thank you for reading.
How to customize the serializer https://www.baeldung.com/jackson-custom-serialization
About toPlainString https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/math/BigDecimal.html#toPlainString() https://qiita.com/shotana/items/e02357516798e6bc658e
Recommended Posts