Flutter - 字符编码未按预期运行
Flutter - Character encoding is not behaving as expected
我正在解析一个本地 JSON
文件,该文件包含 冰岛语中很少使用的特殊字符。
在显示字符时,我混淆了符号而不是字符,对于其他一些,我只混淆了一个正方形而不是一个符号。
我正在使用这种类型的编码"\u00c3"
更新: 我使用的字符示例:þ, æ, ý, ð
问:显示这些字符并避免显示失败的最佳方法是什么?
更新#2:
我是如何解析的:
Future<Null> getAll() async{
var response = await
DefaultAssetBundle.of(context).loadString('assets/json/dictionary.json');
var decodedData = json.decode(response);
setState(() {
for(Map word in decodedData){
mWordsList.add(Words.fromJson(word));
}
});
}
class:
class Words{
final int id;
final String wordEn, wordIsl;
Words({this.id, this.wordEn, this.wordIsl});
factory Words.fromJson(Map<String, dynamic> json){
return new Words(
id: json['wordId'],
wordEn: json['englishWord'],
wordIsl: json['icelandicWord']
);
}
}
JSON 型号:
{
"wordId": 47,
"englishWord": "Age",
//Here's a String that has two special characters
"icelandicWord": "\u00c3\u00a6vi"
}
问题是您的 JSON 存储在本地。
假设你有
Map<String, String> jsonObject = {"info": "Æ æ æ Ö ö ö"};
因此,为了正确显示您的文本,您必须使用 utf-8 对 JSON 进行编码和解码。
我知道序列化和反序列化是昂贵的操作,但它是本地存储的包含 UTF-8 文本的 JSON 对象的解决方法。
import 'dart:convert';
jsonDecode(jsonEncode(jsonObject))["info"]
如果你从服务器获取 JSON,那么它就简单多了,例如在 dio
包中你可以选择 contentType
参数,默认情况下是 "application/json; charset=utf-8" .
我对重音字符有类似的问题。它们没有按预期显示。
这对我有用
final codeUnits = source.codeUnits;
return Utf8Decoder().convert(codeUnits);
我正在解析一个本地 JSON
文件,该文件包含 冰岛语中很少使用的特殊字符。
在显示字符时,我混淆了符号而不是字符,对于其他一些,我只混淆了一个正方形而不是一个符号。
我正在使用这种类型的编码"\u00c3"
更新: 我使用的字符示例:þ, æ, ý, ð
问:显示这些字符并避免显示失败的最佳方法是什么?
更新#2: 我是如何解析的:
Future<Null> getAll() async{
var response = await
DefaultAssetBundle.of(context).loadString('assets/json/dictionary.json');
var decodedData = json.decode(response);
setState(() {
for(Map word in decodedData){
mWordsList.add(Words.fromJson(word));
}
});
}
class:
class Words{
final int id;
final String wordEn, wordIsl;
Words({this.id, this.wordEn, this.wordIsl});
factory Words.fromJson(Map<String, dynamic> json){
return new Words(
id: json['wordId'],
wordEn: json['englishWord'],
wordIsl: json['icelandicWord']
);
}
}
JSON 型号:
{
"wordId": 47,
"englishWord": "Age",
//Here's a String that has two special characters
"icelandicWord": "\u00c3\u00a6vi"
}
问题是您的 JSON 存储在本地。
假设你有
Map<String, String> jsonObject = {"info": "Æ æ æ Ö ö ö"};
因此,为了正确显示您的文本,您必须使用 utf-8 对 JSON 进行编码和解码。
我知道序列化和反序列化是昂贵的操作,但它是本地存储的包含 UTF-8 文本的 JSON 对象的解决方法。
import 'dart:convert';
jsonDecode(jsonEncode(jsonObject))["info"]
如果你从服务器获取 JSON,那么它就简单多了,例如在 dio
包中你可以选择 contentType
参数,默认情况下是 "application/json; charset=utf-8" .
我对重音字符有类似的问题。它们没有按预期显示。 这对我有用
final codeUnits = source.codeUnits;
return Utf8Decoder().convert(codeUnits);