自学内容网 自学内容网

Java:swagger/knife4j接口返回的json数据中文显示乱码问号???

问题描述

正常接口的中文返回是正确的
而只要发生异常处理,就会使用全局统一异常处理,输出包含中文字符的json字符串,发现,全都变成了问号??????

/**
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(Throwable error, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.write("{\"code\":1,\"data\":null,\"msg\":\"请勿重复订阅\"}");
    }
}

输出如下

{"code":1,"data":null,"msg":"??????"}

问题解决

设置响应头的内容字符编码即可

// 设置响应编码
response.setContentType("application/json;charset=utf-8");

PrintWriter writer = response.getWriter();
writer.write("{\"code\":1,\"data\":null,\"msg\":\"请勿重复订阅\"}");

输出如下

{"code":1,"data":null,"msg":"请勿重复订阅"}

参考文章

Servlet中使用JSON.toJSONString中文显示问号解决办法


原文地址:https://blog.csdn.net/mouday/article/details/140719028

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!