欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

@ResponseBody注解支持的json包

程序员文章站 2022-07-12 19:41:24
...

起因,@ResponseBody注解在引用FastJson包的情况下失效。考虑到@ResponseBody只支持Jackson,故去看一看源码是如何调用的
查看注解扫描源码<mvc:annotation-driven/>
@ResponseBody注解支持的json包
进入RequestMappingHandlerAdapter中查看
@ResponseBody注解支持的json包
会发现构造器中引入诸多HttpMessageConverter,其中还有AllEncompassingFormHttpMessageConverter,进入查看

public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConverter {
    private static final boolean jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
    private static final boolean jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
    private static final boolean jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
    private static final boolean gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", AllEncompassingFormHttpMessageConverter.class.getClassLoader());

    public AllEncompassingFormHttpMessageConverter() {
        this.addPartConverter(new SourceHttpMessageConverter());
        if(jaxb2Present && !jackson2XmlPresent) {
            this.addPartConverter(new Jaxb2RootElementHttpMessageConverter());
        }

        if(jackson2Present) {
            this.addPartConverter(new MappingJackson2HttpMessageConverter());
        } else if(gsonPresent) {
            this.addPartConverter(new GsonHttpMessageConverter());
        }

        if(jackson2XmlPresent) {
            this.addPartConverter(new MappingJackson2XmlHttpMessageConverter());
        }

    }
}

可以发现默认其支持Jackson和Gson,并不支持FastJson
源码基于spring4.3.10

另外,在所支持的json中已配置默认字符集为utf-8
查看GsonHttpMessageConverter构造器
@ResponseBody注解支持的json包
查看MappingJackson2HttpMessageConverter构造器
@ResponseBody注解支持的json包
其调用了父类的构造器,再去看父类里面看
@ResponseBody注解支持的json包
可以看见默认字符集都是utf-8

如果不使用所支持的Jackson和Gson,则需要注意字符集的问题
可在@RequestMapping注解中使用produces来配置charset
@RequestMapping(value = "demo", produces = "application/json;charset=utf-8")