【发布时间】:2021-12-16 08:06:41
【问题描述】:
我正在我的 Flutter 应用程序中解析一个 html 页面,并且在该 html 源代码中间的某处有一个 utf-8 格式(“\x”格式)的 json 字符串。
我能够获取 html 内容,然后对其进行解析,将 "\x" utf-8 格式的 json 对象提取为 String var,但我无法将其转换为 json 以对其进行解码.
我尝试在解析的输出“\x5B”中打印前 4 个字母的 ranes,它打印为 4 个单独的整数,而我静态分配给 String var 并打印了相同的“\x5B”,它只显示一位数。所以只是想知道如何以“\x”格式解码提取的字符串?
代码摘录如下:
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var res = utf8.decode(response.bodyBytes);
//gives the starting index of json object in html source
int startIndex = res.indexOf('var statData');
// start and end index of json object in "\x" format
int start = res.indexOf("(", startIndex) + 2;
int end = res.indexOf(");", start) - 1;
//extract the json in \x encoded
String dataJson = res.substring(start,end);
//now sample code to compare the string, one statically assigned,
//another extracted from the html source, to describe the issue I'm having now.
String sample1 = dataJson.substring(0,4)); //extracts "\x5B" from the string
String sample2 = "\x5B";
print(sample2.runes); // prints (91)
print(sample1.ranes); // prints (92, 120, 53, 66), expectation is to get (91)
}
输出:
I/flutter ( 3437): (91) I/flutter ( 3437): (92, 120, 53, 66)
而 sample2.runes 打印单个字符 (91)(等效 ascii 是 '{' - json 的开头)),
我从字符串中提取的相同“\x5B”没有被解码为 (91),而是被视为 4 个单独的字符,因此看起来“\x”提取的字符串不被视为 utf-8 编码指示符。
我希望 sample1.runes 也是 {91},如何处理?,我哪里错了?
【问题讨论】:
-
你需要this 之类的东西(对不起,我不会说 Dart……)
-
感谢@JosefZ,是的,非常相似,在 Python 中,我能够通过这样做使其工作,
res.encode("utf8").decode("unicode_escape")。试图找到与之等效的 Dart/flutter。
标签: json flutter http utf-8 character-encoding