美文网首页
springboot配置fastjson 解析---- 返回js

springboot配置fastjson 解析---- 返回js

作者: weylan | 来源:发表于2018-02-02 17:35 被阅读1557次

springboot默认采用的是jackson解析json,在未进行配置的情况下会出现值为空的键丢失的情况,网上有配置的方案,但不能解决全部问题,这里采用更换json解析工具的解决办法,

引入fastjson jar包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>${fastjson.version}</version>
</dependency>

添加configbean

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

@Configuration
public class BeanConfig {

    /*注入Bean : HttpMessageConverters,以支持fastjson*/
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.DisableCheckSpecialChar);
        fastJsonConfig.setDateFormat("yyyy-MM-dd hh:mm:ss");
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConvert.setSupportedMediaTypes(fastMediaTypes);
        fastConvert.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters((HttpMessageConverter<?>) fastConvert);
    }
}

fastjon 的详细配置 在这篇文章中讲的很详细,就不一 一叙述了
http://blog.csdn.net/u010246789/article/details/52539576

相关文章

网友评论

      本文标题:springboot配置fastjson 解析---- 返回js

      本文链接:https://www.haomeiwen.com/subject/ysvezxtx.html