从服务器中提取的日语字符解码错误

从服务器中提取的日语字符解码错误

本文介绍了Flutter 从服务器中提取的日语字符解码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Flutter 构建一个移动应用.

I am building a mobile app with Flutter.

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

I need to fetch a json file from server which includes Japanese text. A part of the returned json is:

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

在 postman 或 chrome 上尝试相同的请求会给出预期的结果(日语字符在输出中正确呈现).

Trying the same request on postman or chrome gives the expected result (Japanese characters are rendered properly in the output).

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

But when the data is fetched with Dart by the following code snippet:

  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语句的结果是

The result of the print statement in logcat is

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

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

Note that only the Japanese characters (value of the content key) is turns into gibberish, the other non-Japanese values are still displayed properly.

两个通知是:

  1. 如果我尝试通过 Text() 在我的应用程序中显示此日语文本,则会呈现相同的乱码,因此这不是 Android Studio 的 logcat 的错误.
  2. 如果我使用Text('put some Japanese text here directly') (ex: Text('睡眠')),Flutter 显示正确,所以它是不是弄乱日文字符的 Text 小部件.
  1. If I try to display this Japanese text in my app via Text(), the same gibberish is rendered, so it is not a fault of Android Studio's logcat.
  2. If I use Text('put some Japanese text here directly') (ex: Text('睡眠')), Flutter displays it correctly, so it is not the Text widget that messes up the Japanese characters.

推荐答案

如果你查看 postman,你可能会看到服务器发送的 Content-Type http 头缺少 编码 标签.这会导致 Dart http 客户端将正文解码为 Latin-1 而不是 utf-8.有一个简单的解决方法:

If you look in postman, you will probably see that the Content-Type http header sent by the server is missing the encoding tag. This causes the Dart http client to decode the body as Latin-1 instead of utf-8. There's a simple workaround:

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

这篇关于Flutter 从服务器中提取的日语字符解码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:26