Flutter 从服务器中获取日语字符解码错误

Flutter fetched Japanese character from server decoded wrong

我正在使用 Flutter 构建移动应用程序。

我需要从服务器获取一个包含日语文本的 json 文件。返回的 json 的一部分是:

{
     "id": "egsPu39L5bLhx3m21t1n",  
     "userId": "MCetEAeZviyYn5IMYjnp",  
     "userName": "巽 裕亮",  
     "content": "フルマラソン完走に対して2018/05/06のふりかえりを行いました!"
}

对 postman 或 chrome 尝试相同的请求会得到预期的结果(日文字符在输出中正确呈现)。

但是当通过以下代码片段用Dart获取数据时:

  import 'dart:convert';
  import 'package:http/http.dart' as http;

  //irrelevant parts have been omitted    
  final response = await http.get('SOME URL',headers: {'Content-Type': 'application/json'});
  final List<dynamic> responseJson = json.decode(response.body)
  print(responseJson);

logcat中print语句的结果是

{
     id: egsPu39L5bLhx3m21t1n, 
     userId: MCetEAeZviyYn5IMYjnp, 
     userName: å·½ è£äº®, 
     content: ãã«ãã©ã½ã³å®èµ°ã«å¯¾ãã¦2018/05/06ã®ãµãããããè¡ãã¾ããï¼
}

请注意,只有日文字符(content 键的值)变成乱码,其他非日文值仍可正常显示。

两个通知是:

  1. 如果我尝试通过 Text() 在我的应用程序中显示此日语文本,则会呈现相同的乱码,因此这不是 Android Studio 的 logcat 的错误。
  2. 如果我使用 Text('put some Japanese text here directly')(例如:Text('睡眠')),Flutter 会正确显示它,所以不是 Text 小部件弄乱了日语字符。

如果您查看 postman,您可能会发现服务器发送的 Content-Type http header 缺少 encoding 标记。这会导致 Dart http 客户端将 body 解码为 Latin-1 而不是 utf-8。有一个简单的解决方法:

http.Response response = await http.get('SOME URL',headers: {'Content-Type': 'application/json'});
List<dynamic> responseJson = json.decode(utf8.decode(response.bodyBytes));

就这么简单! 而不是使用 response.body;你应该使用 utf8.decode(response.bodyBytes)