我正在用Flutter构建一个移动应用程序.
我需要json从服务器获取包含日文文本的文件.返回的一部分json是:
{
"id": "egsPu39L5bLhx3m21t1n",
"userId": "MCetEAeZviyYn5IMYjnp",
"userName": "? ??",
"content": "????????????2018/05/06?????????????"
}
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
printlogcat 中的语句结果是
{
id: egsPu39L5bLhx3m21t1n,
userId: MCetEAeZviyYn5IMYjnp,
userName: å·½ è£äº®,
content: ãã«ãã©ã½ã³å®èµ°ã«å¯¾ãã¦2018/05/06ã®ãµãããããè¡ãã¾ããï¼
}
Run Code Online (Sandbox Code Playgroud)
请注意,只有日文字符(content键的值)变为乱码,其他非日语值仍然正确显示.
两个通知是:
Text()则会呈现相同的乱码,因此这不是Android Studio的logcat的错误.Text('put some Japanese text here directly')(例如Text('??'):),Flutter会正确显示它,因此不是Text小部件会弄乱日文字符.我正在使用渡槽网络API框架来支持我的flutter应用程序。在我的api后端中,我需要连接本地网络套接字服务。我的问题是我无法返回确切的字符串(在tr中)。S o,如何在Dart中将字符串转换为utf8?
例:
@httpGet
Future<Response> getLogin() async {
Socket.connect('192.168.1.22’, 1024).then((socket) async {
socket.listen((data) {
// Expected return is: 1:_:2:_:175997:_:N?YAZ? TOROS
print(new String.fromCharCodes(data).trim());
xResult = new String.fromCharCodes(data).trim();
print("xResult: $xResult");
}, onDone: () {
print("Done");
socket.destroy();
});
socket.write('Q101:_:49785:_:x\r\n');
});
return new Response.ok(xResult);
}
Run Code Online (Sandbox Code Playgroud)
返回值不是TR-tr语言格式。
返回文本如下: 1::2::175997:_:NÝYAZÝTOROS
正确的必须是: 1::2::175997:_:N?YAZ?托罗斯
更新:
xResult = new String.fromCharCodes(data).trim();print(xResult);responseBody = xResult.transform(utf8.decoder);print(responseBody);我可以打印,xResult但responseBody尝试转换为UTF8后无法打印。