Flutter从服务器中获取日语字符,解码错误 [英] Flutter fetched Japanese character from server decoded wrong
问题描述
我正在使用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のふりかえりを行いました!"
}
在邮递员或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.
两个注意事项是:
- 如果我尝试通过
Text()
在我的应用程序中显示此日语文本,则会呈现相同的乱码,因此这不是Android Studio的logcat的错误。 - 如果我使用
Text('在此处直接输入一些日语文本')
(例如:Text('睡眠')
),Flutter会正确显示它,因此不是Text
小部件会弄乱日语字符。
- 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. - If I use
Text('put some Japanese text here directly')
(ex:Text('睡眠')
), Flutter displays it correctly, so it is not theText
widget that messes up the Japanese characters.
推荐答案
如果查看邮递员,您可能会发现 Content-Type 服务器发送的code> http标头缺少
encoding
标记。这会导致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从服务器中获取日语字符,解码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!