问题
主键 Long 型返回到前端丢失精度问题
两种简单的解决方式:
- @JSONField(serializeUsing = ToStringSerializer.class)
2.@JsonSerialize(using = LongToStringSerializer.class)
fastjson
中的ToStringSerializer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ToStringSerializer implements ObjectSerializer {
public static final ToStringSerializer instance = new ToStringSerializer();
@Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.out; if (object == null) { out.writeNull(); return; } String strVal = object.toString(); out.writeString(strVal); } }
|
自定义类 LongToStringSerializer
1 2 3 4 5 6 7 8 9 10
| public class LongToStringSerializer extends JsonSerializer<Long> { @Override public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (value == null) { gen.writeNull(); return; } gen.writeString(value.toString()); } }
|
一劳永逸的解决方式(序列化、反序列化)
此解决方案是 springboot
中使用jackson
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
@Component public class BootWebMvcConfigurer implements WebMvcConfigurer {
@Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class , new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_DATETIME_FORMAT))); javaTimeModule.addSerializer(LocalDate.class , new LocalDateSerializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_DATE_FORMAT))); javaTimeModule.addSerializer(LocalTime.class , new LocalTimeSerializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_TIME_FORMAT))); javaTimeModule.addDeserializer(LocalDateTime.class , new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_DATETIME_FORMAT))); javaTimeModule.addDeserializer(LocalDate.class , new LocalDateDeserializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_DATE_FORMAT))); javaTimeModule.addDeserializer(LocalTime.class , new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DateBootUtil.DEFAULT_TIME_FORMAT))); javaTimeModule.addSerializer(Long.class , new LongToStringSerializer()); objectMapper.registerModule(javaTimeModule); return objectMapper; } }
|
本文地址: https://github.com/maxzhao-it/blog/post/45ed5038/