SpringBoot配置FastJson并解决乱码问题

1.导入Jar包,我用的Gradle,导入方式如下(最后一个)

dependencies {
    //热部署
    compile("org.springframework.boot:spring-boot-devtools")
    //spring mvc
    compile("org.springframework.boot:spring-boot-starter-web")
    //设置程序监控
    compile("org.springframework.boot:spring-boot-starter-actuator")
    //数据库配置
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.alibaba:druid:1.0.23")
    compile("mysql:mysql-connector-java:$mysqlVersion")
    testCompile("org.springframework.boot:spring-boot-starter-test")
    //缓存
    compile("org.springframework.boot:spring-boot-starter-cache")
    //配置fastJson
    compile("com.alibaba:fastjson:1.2.24")
}

2.在项目中写一个配置类

package com.kingboy.springboot.config;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.kingboy.springboot.domain.JsonEntiry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

import static com.alibaba.fastjson.serializer.SerializerFeature.UseISO8601DateFormat;
import static com.alibaba.fastjson.serializer.SerializerFeature.WriteDateUseDateFormat;


@Configuration
public class FastJson{
    protected FastJson() {
    }

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteClassName,//输出类名字
                SerializerFeature.WriteMapNullValue
        );
        ValueFilter valueFilter = new ValueFilter() {
            //o 是class
            //s 是key值
            //o1 是value值
            public Object process(Object o, String s, Object o1) {
                if (null == o1){
                    o1 = "";
                }
                return o1;
            }
        };
        fastJsonConfig.setSerializeFilters(valueFilter);
        //可以设置编码,默认UTF-8
        //fastJsonConfig.setCharset(Charset.forName("UTF-8"));

        converter.setFastJsonConfig(fastJsonConfig);

        return converter;
    }
}

3. 在配置文件中指定要使用的Json转换类

application.properties

#配置Json转换器
spring.http.converters.preferred-json-mapper=fastjson

实验了下,不导入这个配置,仍然会自动用fastJson代替Jackson,有知道原理的解惑下。

4.解决乱码

当我使用fastJson之后,返回页面的中文乱码,看了fastJson的源码默认使用UTF-8;

public class FastJsonHttpMessageConverter //
        extends AbstractHttpMessageConverter<Object> //
        implements GenericHttpMessageConverter<Object> {

    @Deprecated
    protected Charset charset = IOUtils.UTF8;

    @Deprecated
    protected SerializerFeature[] features = new SerializerFeature[0];

    @Deprecated
    protected SerializeFilter[] filters = new SerializeFilter[0];

    @Deprecated
    protected String dateFormat;

    ....

所以判断可能是springboot的返回编码不对。接着看springboot原代码。

启动的时候走到这个断点。

这里写图片描述

看下具体的值,forceResponseEncoding 为false,这时候默认的返回编码就是系统的编码了。所以接下来把springboot的response编码设置为utf-8这个功能开启就好。

这里写图片描述

开启方式:

application.properties

#配置response编码
#spring.http.encoding.charset=UTF-8
#spring.http.encoding.enable=true
spring.http.encoding.force=true
Fastjson引入Spring Boot项目的步骤有: 1. 添加Fastjson maven依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 2. 配置FastjsonSpringBoot项目的启动类中添加如下代码: ``` @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Configuration public class FastJsonConfig { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1.定义一个converters转换消息的对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // 2.添加fastjson配置信息,比如:是否要格式化返回的json数据 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat ); // 3.在converter中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } } } ``` 3. 使用Fastjson 在Controller或Service中,使用Fastjson进行数据的序列化和反序列化。例如: ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("/") public String addUser(@RequestBody User user) { userService.addUser(user); return "success"; } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值