【问题标题】:How to decode utf-8 from REST api in Dart code?如何在 Dart 代码中从 REST api 解码 utf-8?
【发布时间】:2019-05-13 04:09:27
【问题描述】:

我正在尝试使用 REST API 从 Wordpress 网站创建新闻报道应用,但它以 UTF-8 编码。

我是 Dart 的新手,我只知道我可以仅通过字符数组而不是通过提供字符串(作为输入)来解码 Utf-8。那么如何为我的应用解码 Utf-8 中的字符串?

child: new Text(posts[index]["title"]['rendered'],
                                style: TextStyle(
                                  fontSize: 21,
                                  fontWeight: FontWeight.bold,
                                ),
                                textAlign: TextAlign.center),
                          ),
                          new Padding(
                            padding: EdgeInsets.all(10.0),
                            child: new ListTile(
                              subtitle: new Text(posts[index]["excerpt"]
                                      ["rendered"]
                                  .replaceAll(new RegExp(r'<[^>]*>'), '')),
                            ),
                          ),

这是结果的图片:https://imgur.com/gallery/qxkc9yP

【问题讨论】:

  • 一般情况下,您可以使用dart:convertutf8.decode()函数将UTF-8编码的Uint8List解码为String。你说你已经有一个String,但你没有说你是怎么到达那个位置的。

标签: html utf-8 dart flutter


【解决方案1】:

您可以获取正文字节并将其转换..

 http.Response response = await _api.getData();
 String source = Utf8Decoder().convert(response.bodyBytes);

 // Convert to your class instance...
 MyClass instance = json.decode(source);

【讨论】:

  • 谢谢@siega,我是 Flutter 和 Dart 的新手,你的回答确实帮助我修复了字符编码!
  • 根据ietf.org/rfc/rfc4627.txt,这种行为(技术上)不是错误的吗?它在其第 3 节中声明:“JSON 文本应以 Unicode 编码。默认编码为 UTF-8。”因此,如果 Content-Type 是“application/json”(没有 charset=utf-8),http 不应该使用 utf-8 自动解码正文吗?
猜你喜欢
  • 2021-10-13
  • 2012-08-23
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
相关资源
最近更新 更多