当使用@RestController注解时,会把响应信息自动解析成json格式,使用的是Jackson,但是Jackson默认不解析key为null的映射时会抛出异常,需要增加配置;
解决:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.io.IOException;
/**
* Jackson解析配置
* @author YanZhen
* @date 2022/03/15 19:23
*/
@Configuration
public class JacksonConverterConfig {
/**
* @return 重写Jackson解析配置
*/
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().build();
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 当值为null时舍弃序列化
// 当Jackson解析map时,key为null转为空,防止com.fasterxml.jackson.databind.JsonMappingException异常
objectMapper.getSerializerProvider().setNullKeySerializer(new JsonSerializer<Object>(){
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeFieldName("");
}
});
return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
可以设置成任何占位,只要你需要!!!
|