Handling Large Integer IDs in Java and JavaScript: Preventing Precision Loss with Jackson Configuration
When generating large IDs using Snowflake-like algorithms, Java's 64‑bit long values exceed JavaScript's safe integer range, causing display errors; the article explains how to resolve this by serializing Long values as strings in Spring Boot using Jackson's ToStringSerializer, both via configuration and annotations.
When sensitive data IDs are generated with a Snowflake‑style algorithm, the resulting values are stored as Java long (max 9223372036854775807). In browsers, especially Chrome, these large numbers cannot be displayed correctly because JavaScript's safe integer limit (2^53‑1) is much smaller.
The article shows screenshots of the discrepancy and points out that JavaScript integers lose precision for the higher bits of a Java long , leading to incorrect values on the front end.
To solve the problem, the back‑end can serialize Long values as strings so that the front‑end receives the exact identifier without precision loss. A Spring Boot solution is provided by customizing Jackson's object mapper.
@Configuration
public class Jackson2Customizer {
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder -> {
// Fix front‑end JS precision issue
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
jacksonObjectMapperBuilder.simpleDateFormat(DATE_TIME_FORMAT);
};
}
}Alternatively, individual fields can be annotated directly:
@JsonSerialize(using = ToStringSerializer.class)By converting Long values to strings during JSON serialization, the front‑end receives the full identifier without truncation, eliminating the display issue.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.