【问题标题】:Flutter - Convert "\x" encoded utf-8 characters to readable String from http.get responseFlutter - 将“\x”编码的 utf-8 字符转换为来自 http.get 响应的可读字符串
【发布时间】: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


【解决方案1】:

我不知道这是否是正确的处理方式,但感谢这篇文章https://stackoverflow.com/a/64699290/17301137 ,我能够解决它。

基本上它对'\x'之后的所有十六进制值进行正则表达式匹配,然后将其替换为相应的字符串返回。

final Pattern unicodePattern = new RegExp(r'\\x([0-9A-Fa-f]{2})');
final String newStr = sample1.replaceAllMapped(unicodePattern, (Match unicodeMatch) {
  final int hexCode = int.parse(unicodeMatch.group(1)!, radix: 16);
  final unicode = String.fromCharCode(hexCode);
  return unicode;
});

我就是这样解决的。

但不确定,是否有更好的解决方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2011-05-20
    • 2011-08-16
    • 2016-10-01
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多