spring web mvc 集成 fastjson2

发布时间 2023-08-23 19:45:57作者: 修烛

maven依赖

参考文档 https://github.com/alibaba/fastjson2/blob/main/docs/spring_support_cn.md

<!- spring5 使用这个 ->
<dependency> 
    <groupId>com.alibaba.fastjson2</groupId> 
    <artifactId>fastjson2-extension-spring5</artifactId> 
    <version>2.0.39</version> 
</dependency>

<!- spring6 使用这个 ->
<dependency> 
    <groupId>com.alibaba.fastjson2</groupId> 
    <artifactId>fastjson2-extension-spring6</artifactId> 
    <version>2.0.39</version> 
</dependency>


<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.24</version>
</dependency>

spring mvc集成

image.png

@Configuration
public class JsonMessageConverterConfigurer implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 自定义配置...
        FastJsonConfig config = new FastJsonConfig();
        config.setWriterFeatures(JSONWriter.Feature.WriteEnumsUsingName, JSONWriter.Feature.IgnoreNonFieldGetter);
        converter.setFastJsonConfig(config);

        // spring boot高版本无需配置,低版本不配置报错:Content-Type cannot contain wildcard type '*'
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(fastMediaTypes);

        JSON.register(JsonObject.class, new ObjectWriter<JsonObject>() {
            @Override
            public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
                JsonObject jsonObject = (JsonObject) object;
                if (jsonObject == null) {
                    jsonWriter.writeNull();
                }
                Gson gson = new Gson();
                String s = gson.toJson(jsonObject);
                jsonWriter.writeString(s);
            }
        });

        converters.add(0,converter);
    }
}