[JAVA] [Jackson] A story about converting the return value of BigDecimal type with a custom serializer.

Introduction

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.

Solution

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

Summary

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.

References

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

[Jackson] A story about converting the return value of BigDecimal type with a custom serializer.
A story about hitting the League Of Legends API with JAVA
About the treatment of BigDecimal (with reflection)
Declare a method that has a Java return value with the return value data type
The story of making a reverse proxy with ProxyServlet
A story packed with the basics of Spring Boot (solved)
[Rails] Talk about paying attention to the return value of where
A story that struggled with the introduction of Web Apple Pay
The story of making a communication type Othello game using Scala.
A monad is a design pattern for "expressing the existence of side effects in a method with a return type".
The story of making a game launcher with automatic loading function [Java]
The story of encountering Spring custom annotation
A story about the JDK in the Java 11 era
The story of tuning android apps with libGDX
A story about making a Builder that inherits the Builder
Specify the default value with @Builder of Lombok
Write a test by implementing the story of Mr. Nabeats in the world with ruby
Pass arguments to the method and receive the result of the operation as a return value
Sample code to assign a value in a property file to a field of the expected type
[PHP] A story about outputting PDF with TCPDF + FPDI
A story about trying to get along with Mockito
Display the average value of the evaluation as a star
A story about reducing memory consumption to 1/100 with find_in_batches
A story about introducing Evolutions into the Play Framework
A story about developing ROS called rosjava with java
I learned about the existence of a gemspec file
The story of making dto, dao-like with java, sqlite
A story about making catkin_make of rosjava compatible offline
The story of pushing a Docker container to GitHub Package Registry and Docker Hub with GitHub Actions
The story of building a Java version of Minecraft server with GCP (and also set a whitelist)
I want to return a type different from the input element with Java8 StreamAPI reduce ()
[First post] A story about a second new graduate of PE becoming a programmer with no experience
A story I was addicted to with implicit type conversion of ActiveRecord during unit testing
[Automatic trading of Bitcoin] A story about operating with Docker on AWS, with 1 TAP ON / OFF & Line notification from Apple Watch on the go