【问题标题】:Dart Json UTF-8 DecodeDart Json UTF-8 解码
【发布时间】:2021-10-13 06:29:43
【问题描述】:

我需要将收到的数据解码为 utf8。代码是这样的

Future<Products> Get Product() async {
     var response = await http.get(url);
     var decodedJson = json.decode(response.body);
     products = Products.fromJson(decodedJson);
     return products;
   }

我尝试了我看到的解决方案。其中一个告诉我这样做

 var response = await http.get(url,headers: {'Content-Type': 'application/json'});
 var decodedJson = json.decode(utf8.decode(response.bodyBytes));

当我这样做时,我得到以下信息

errorException has occurred.
FormatException (FormatException: Missing extension byte (at offset 554))

) 它看起来像

【问题讨论】:

  • 您是否从 API 获取数据?
  • 您的 bodyBytes 似乎不包含有效的 UTF-8。你确定你不会为你的请求设置一个字符集吗?响应中设置了什么字符集?
  • @RavindraS.Patil 是的,我正在获取数据并使用它。但写的是 ''ARAÇ TEMİZLEYİCİ'' 而不是 ''ARAÇ TEMÝZLEYÝCÝ''
  • @julemand101 实际上,我不明白你的意思。我是开发人员世界的新手。字符集是什么意思?
  • 如果您从 API 获取数据,请参考我的回答 hereherehere 希望对您有所帮助。

标签: json flutter api dart utf-8


【解决方案1】:

试试这个代码

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Products> Get Product() async {
      final response = await http
          .get(Uri.parse(url));
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
        return Products.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load Products');
      }
      
    }

【讨论】:

  • 我认为 OP 得到错误响应或任何与成功不同的东西(200-299 代码)。因此,当您说明响应是否成功(200)时,此答案应该有助于解决问题。可能错误响应返回空正文
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 2012-06-26
  • 1970-01-01
  • 2018-11-05
  • 2015-07-22
相关资源
最近更新 更多