Spring Boot集成fastjson并设置字符集为UTF-8

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

首先加入fastjson


    com.alibaba
    fastjson
    1.2.56

在 Spring MVC 中集成 Fastjson

/**
 * 在spring boot 2.x中,直接实现WebMvcConfigurer接口即可,得益于Java8中的默认方法,WebMvcConfigurerAdapter已经过时
 * @author [email protected]
 * @date 2019/3/4
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    /**
     * 在 Spring MVC 中集成 FastJson
     */
    public void configureMessageConverters(List> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //自定义配置...
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(WriteNullListAsEmpty,
                                    WriteNullStringAsEmpty,
                                    WriteNullNumberAsZero,
                                    WriteNullBooleanAsFalse,
                                    WriteMapNullValue);

        //处理中文乱码问题
        List fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(fastMediaTypes);

        converter.setFastJsonConfig(config);
        // 下面这行代码是在spring boot 1.x中使用,并且配置类需要继承WebMvcConfigurerAdapter
        // converters.add(converter);
        /*
        SpringBoot 2.0.1版本中加载WebMvcConfigurer的顺序发生了变动,故需使用converters.add(0, converter);
        指定FastJsonHttpMessageConverter在converters内的顺序,
        否则在SpringBoot 2.0.1及之后的版本中将优先使用Jackson处理
         */
        converters.add(0, converter);
    }

    /**
     * 对JSONP支持. 使用注解@ResponseJSONP修饰类或具体方法:
     */
    @Bean
    public JSONPResponseBodyAdvice jsonpResponseBodyAdvice() {
        return new JSONPResponseBodyAdvice();
    }
    
}

在 Spring Data Redis 中集成 Fastjson

/**
 * AutoConfigureAfter是让我们这个配置类在内置的配置类之后在配置,这样就保证我们的配置类生效,并且不会被覆盖配置
 * @author [email protected]
 * @date 2019/3/4
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * 在 Spring Data Redis 中集成 FastJson,使用RedisTemplate的时候,可以加入泛型,避免到处转换
     * Autowired
     * private RedisTemplate  redisTemplate;
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);//设置默认的Serialize,包含 keySerializer & valueSerializer

        //redisTemplate.setKeySerializer(fastJsonRedisSerializer);//单独设置keySerializer
        //redisTemplate.setValueSerializer(fastJsonRedisSerializer);//单独设置valueSerializer
        return redisTemplate;
    }

}

 

转载于:https://my.oschina.net/hutaishi/blog/1531585

你可能感兴趣的:(Spring Boot集成fastjson并设置字符集为UTF-8)