Skip to content

Instantly share code, notes, and snippets.

@lvxianchao
Created December 28, 2022 01:21
Show Gist options
  • Save lvxianchao/fb7eddf95c132b182069cb7ba5a2d74b to your computer and use it in GitHub Desktop.
Save lvxianchao/fb7eddf95c132b182069cb7ba5a2d74b to your computer and use it in GitHub Desktop.
Java 将 Long 类型转换为 String 类型以解决前端精度丢失问题
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.math.BigInteger;
/**
* Date: 2022-12-28 09:00
* Description: 将 Long 类型转换为 String 类型,以解决前端精度丢失问题
*/
@Configuration
public class LongToStringConfig implements InitializingBean {
@Resource
ObjectMapper objectMapper;
@Override
public void afterPropertiesSet() throws Exception {
SimpleModule simpleModule = getSimpleModule();
objectMapper.registerModule(simpleModule);
}
private SimpleModule getSimpleModule() {
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return simpleModule;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment