【问题标题】:JSON http.get return áá flutterJSON http.get 返回 áá flutter
【发布时间】:2020-05-20 23:39:00
【问题描述】:

我正在尝试从 URL 链接检索 JSON。 JSON 数据包含英语和缅甸语。但是,当我检索数据时,该应用程序显示了一堆转换为“áá”的缅甸语单词。有什么解决办法吗?


class _GetJsonResultState extends State<GetJsonResult> {
  @override
  Widget build(BuildContext context) {
    var jsonFileName = "assets/resultlist/resultlist.json";

    fetchData() async {
    final response =
    await http.get('https://jsonkeeper.com/b/47QP');
    if (response.statusCode == 200) {
      return(response.body);
    }
  }

    return FutureBuilder(
      future: fetchData(),
      builder: (context, snapshot) {
        List myData = json.decode(snapshot.data.toString());
        if (myData == null) {
          return Scaffold(
            body: Center(
              // Loads upon null
              child: CircularProgressIndicator(),
            ),
          );
        } else {
          return Home(myData: myData);
        }
      },
    );
  }
}


这是我应该得到的

【问题讨论】:

    标签: arrays json flutter dart


    【解决方案1】:

    如下更改您的 fetchData() 函数

    fetchData() async {
      final response = await http.get('https://jsonkeeper.com/b/47QP',
          headers: {"charset": "utf-8", "Accept-Charset": "utf-8"});
      if (response.statusCode == 200) {
        return (utf8.decode(response.bodyBytes));
      }
    }
    

    【讨论】:

    • 谢谢!它工作得很好,介意解释一下为什么它不起作用?
    【解决方案2】:

    这是一个解码问题。只是为了澄清背景中发生的事情

    Dart http API 定义(如下所述)与响应数据交互的两种方式:

    body → String
    The body of the response as a string. This is converted from bodyBytes using the charset parameter of the Content-Type header field, if available. If it's unavailable or if the encoding name is unknown, latin1 is used by default, as per RFC 2616.
    
    bodyBytes → Uint8List
    The bytes comprising the body of this response.
    

    更多详情https://github.com/dart-lang/http/issues/175#issuecomment-415721621

    所以在这种情况下,如果您事先知道编码并认为它​​会搞砸,请使用请求编码和字节解码

    fetchData() async {
      final response = await http.get('https://jsonkeeper.com/b/47QP',
          headers: {"charset": "utf-8", "Accept-Charset": "utf-8"});
      if (response.statusCode == 200) {
        return (utf8.decode(response.bodyBytes));
      }
    }
    

    【讨论】:

    • 解释清楚!非常感谢。
    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2021-06-29
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多