Spring-MVC配置Gson做为Message Converter解析Json

Spring-MVC配置Gson做为Message Converter解析Json

在学习Spring的时候看到可以使用@RequestBody 和@ResponseBody注解来是的Spring自动将http 其中的 body(json格式)部分和java内部的类进行转换。同时由于Google Gson的强大一般开发的时候会用的比较多,但是由于Spring内部默认使用的json的message Converter 并不是gson,所以这里需要配置一下才能使其生效;

Spring其实已经在实现了对gson的支持,但是如果想在项目中使用,还需要通过配置一下才可以:

配置文件如下:

    <!--<mvc:annotation-driven/>-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

其中org.springframework.http.converter.json.GsonHttpMessageConverter是Spring已经实现了的,在spring的包中能找到这个类。

注:如果想要某中类型的数据能被Message Converter转换,需要自己实现AbstractGenericHttpMessageConverter这个接口,然后在通过配置文件将这个类加载进你的项目中(比如说alibaba:fastjson,在它包中也实现了度spring message converter 的支持)。

 

备注: 网上有很多实现自己的Message Converter的教程,如果后续需要可以搜一下,实现起来有两个步骤:

  1. 需要自己实现AbstractGenericHttpMessageConverter这个接口;

  2. 通过xml或者其他方法配置一下

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>
    ​
    #在pom下加入依赖
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.3.1</version>
    </dependency>
    @Configuration
    @ConditionalOnClass(Gson.class)
    @ConditionalOnMissingClass(name = "com.fasterxml.jackson.core.JsonGenerator")
    @ConditionalOnBean(Gson.class)
    protected static class GsonHttpMessageConverterConfiguration {
    ​
        @Bean
        @ConditionalOnMissingBean
        public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
            GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
            converter.setGson(gson);
            return converter;
        }
    ​
    }
    ​
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.3.1</version>
    </dependency>
  3. 一下贴点源码:

    package org.springframework.http.converter.json;
    ​
    import com.google.gson.Gson;
    import com.google.gson.JsonIOException;
    import com.google.gson.JsonParseException;
    import com.google.gson.reflect.TypeToken;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.lang.reflect.Type;
    import java.nio.charset.Charset;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpInputMessage;
    import org.springframework.http.HttpOutputMessage;
    import org.springframework.http.MediaType;
    import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
    import org.springframework.http.converter.HttpMessageNotReadableException;
    import org.springframework.http.converter.HttpMessageNotWritableException;
    import org.springframework.util.Assert;
    ​
    public class GsonHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
        public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
        private Gson gson = new Gson();
        private String jsonPrefix;
    ​
        public GsonHttpMessageConverter() {
            super(new MediaType[]{MediaType.APPLICATION_JSON, new MediaType("application", "*+json")});
            this.setDefaultCharset(DEFAULT_CHARSET);
        }
    ​
        public void setGson(Gson gson) {
            Assert.notNull(gson, "'gson' is required");
            this.gson = gson;
        }
    ​
        public Gson getGson() {
            return this.gson;
        }
    ​
        public void setJsonPrefix(String jsonPrefix) {
            this.jsonPrefix = jsonPrefix;
        }
    ​
        public void setPrefixJson(boolean prefixJson) {
            this.jsonPrefix = prefixJson?")]}', ":null;
        }
    ​
        public boolean canRead(Class<?> clazz, MediaType mediaType) {
            return this.canRead(mediaType);
        }
    ​
        public boolean canWrite(Class<?> clazz, MediaType mediaType) {
            return this.canWrite(mediaType);
        }
    ​
        protected boolean supports(Class<?> clazz) {
            throw new UnsupportedOperationException();
        }
    ​
        protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
            TypeToken<?> token = this.getTypeToken(clazz);
            return this.readTypeToken(token, inputMessage);
        }
    ​
        public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
            TypeToken<?> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值