在SpringBoot项目中,接口返回的数据出现LocalDateTime对象被转换成了数组
默认序列化情况下会使用SerializationFeature.WRITE_DATES_AS_TIMESTAMPS。使用这个解析时就会打印出数组。
在WebMvcConfig配置类中扩展Spring Mvc的消息转换器,在此消息转换器中使用提供的对象转换器进行Java对象到json数据的转换:
package com.demo.config
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration // 配置类
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
// 不显示为null的字段
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
// 放到第一个
converters.add(0, jackson2HttpMessageConverter);
}
}
解决后再查看: