Jackson-Long accuracy loss

Explanation

  • Since the maximum accuracy of the certificate in Javascript is limited, the maximum value obtained through the console Number.MAX_SAFE_INTEGERwill be found 9007199254740991that any greater than 9007199254740991 may lose accuracy

And my question is

  • Since our ID is a distributed ID and the data type is Long, it is much larger than the maximum value, so when it is returned to the front end, it will be processed.

deal with

  • jackson2ObjectMapperBuilderCustomizerSolved by customization

/**
 * 修复ID 精度丢失问题
 */
@Configuration
public class JacksonConfig {

    @Bean("jackson2ObjectMapperBuilderCustomizer")
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.serializerByType(Long.class,new CustomLongSerialize());
                jacksonObjectMapperBuilder.serializerByType(Long.TYPE, new CustomLongSerialize());
            }
        };
        return customizer;
    }
}
  • Custom Long serialization
public class CustomLongSerialize extends JsonSerializer<Long> {


    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null && value.toString().length() > 16) {
            gen.writeString(value.toString());
        } else {
            gen.writeNumber(value);
        }
    }
}

Published 20 original articles · Likes0 · Visits 930

Guess you like

Origin blog.csdn.net/vistaed/article/details/104510756