springboot2使用fastjson中文返回问号问题处理

版权声明:powered by 大狼狗郑锴/Moshow魔手 https://blog.csdn.net/moshowgame/article/details/80058823

首先配置FastjsonConverter,核心是设置utf-8的编码。
其次,返回String是会乱码的,这个bug一直都在,但是返回其他object是不会乱码的。所以可以根据接口的请求情况,封装一个返回类,例如我们用ApiReturnObject

/**
 * 添加fastjson的转换
 */
@Configuration
public class FastjsonConverter {

    @Bean
    public HttpMessageConverters customConverters() {
                // 定义一个转换消息的对象

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        // 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();

        // 处理中文乱码问题
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        // 在转换器中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
        stringConverter.setSupportedMediaTypes(fastMediaTypes);

        // 将转换器添加到converters中
        return new HttpMessageConverters(stringConverter,fastConverter);
    }
}

基本返回类型封装

public class ApiReturnObject implements Serializable{

private static final long serialVersionUID = 1L;

private String errorCode="00";
private Object errorMessage;
private Object returnObject;

public ApiReturnObject(String errorCode, Object errorMessage, Object returnObject) {
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.returnObject = returnObject;
}
}

返回工具类封装

public class ApiReturnUtil implements Serializable{

    private static final long serialVersionUID = 1L;

    public static ApiReturnObject error(Object errorMessage) {
        return new ApiReturnObject("01",errorMessage,"");
    }
    public static ApiReturnObject error(Object errorMessage, Object returnObject) {
        return new ApiReturnObject("01",errorMessage,returnObject);
    }
    public static ApiReturnObject success(Object returnObject) {
        return new ApiReturnObject("00","success",returnObject);
    }
    public static ApiReturnObject success(Object errorMessage, Object returnObject) {
        return new ApiReturnObject("00",errorMessage,returnObject);
    }

}

返回工具类调用

@RequestMapping(value="/getQueueByDevice")
    public ApiReturnObject getQueueByDevice(){
        if(成功) {
                    return ApiReturnUtil.success(queueService.getQueueByDevice());
                }else if(出错1){
                    return ApiReturnUtil.error("门票号无效");
                }else{
                    return ApiReturnUtil.error("未预约");
                }
}
阅读更多
换一批

没有更多推荐了,返回首页