1.返回Long转JSON
package com.mingx.drone.config; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; /** * @Description: JavaScript无法精确地表示大于Number.MAX_SAFE_INTEGER(即9007199254740991)的整数 * 返回的数值过大转换为字符串 * @Author: gch * @Date: 2023/9/7 16:39 */ public class IdLongSerializer extends JsonSerializer<Long> { @Override public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (value > 900000000000000L) { gen.writeString(value.toString()); } else { gen.writeNumber(value); } } }
@Bean public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule module = new SimpleModule(); module.addSerializer(Long.class, new IdLongSerializer()); module.addSerializer(Long.TYPE, new IdLongSerializer()); objectMapper.registerModule(module); return objectMapper; }
配置文件中设置日期格式可以解决日期序列化问题
spring: jackson: # 格式化返回时间 yyyy-MM-dd HH:mm:ss date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
不同的情况可以直接在属性上使用注解 优先级高于上述配置文件中配置
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
接收date数据反序列化问题
添加配置文件如下(Date属性测试没问题 DateTime类型没有测试)
package com.mingx.drone.config; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.annotation.Bean; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.TimeZone; @JsonComponent public class DateFormatConfig { @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String pattern; /** * @author xiaofu * @description date 类型全局时间格式化 * @date 2020/8/31 18:22 */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() { return builder -> { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat(pattern); df.setTimeZone(tz); builder.failOnEmptyBeans(false) .failOnUnknownProperties(false) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .dateFormat(df); }; } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern))); } }
标签:jackson,java,接口,数据处理,import,序列化,com,public From: https://www.cnblogs.com/guanxiaohe/p/17843478.html