Dart flutter FormatException:Unicode 转义无效

问题描述

我在我的项目中使用了 http 包并尝试发送 GET 请求并解码收到的 json 但收到错误消息:

E/Flutter ( 2292): [ERROR:Flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Invalid unicode escape (at character 29930)
E/Flutter ( 2292): ...\u0438\u043d)"},{"id":374,"title":"\u041\u0435\u0437\u0430\u0431\u0443\u...

这是我的要求:

var response = await http.get(
  '${ApiConstants.BASE_URL}$path$formattedParams',headers: {
    'accept': "application/json",'Authorization': 'Bearer $token',},);
return json.decode(response.body);

还尝试使用 json 验证器验证服务器响应,在我的情况下,响应是有效的 json。

这是我的 json 响应的一部分,其中捕获错误

{
    "id": 373,"title": "Настурция (Капуцин)"
},{
    "id": 374,"title": "Незабудка" // error is here
},

我该如何解决这个问题?

解决方法

只需以正确的 UTF-8 格式从您的服务器发送响应标头

标题

{
  "Content-Type":"application/json;charset=UTF-8","Charset":"utf-8"
}

Laravel 示例:

return response()->json(
    $data,// response data
    $code,// status code
    [
        'Content-Type' => 'application/json;charset=UTF-8','Charset' => 'utf-8'
    ],JSON_UNESCAPED_UNICODE
);

还要在 android manifest 的 application 元素下添加 useCleartextTraffic 属性。

<application
    android:usesCleartextTraffic="true"
    .....