1. 转换时存在值NULL处理,配置fastjson config
package com.example.demo.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class JsonObjectMapper extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List> converters) {
//1、定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2、添加fastjson的配置信息
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty);
//3、在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
fastConverter.setDefaultCharset(StandardCharsets.UTF_8);
//4、将convert添加到converters中
converters.add(fastConverter);
//5、追加默认转换器
super.addDefaultHttpMessageConverters(converters);
}
}
2. 泛型处理,使用TypeReference
class com.alibaba.fastjson.JSonObject cannot be cast to class com.example.demo.Result
public class Result {
private Integer result;
private List data;
}
Result data = JSONObject.parseObject(result, new TypeReference>(){});