Dart Json UTF-8 解码

问题描述 投票:0回答:2

我需要将收到的数据解码为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))

) 而且看起来像

json flutter api dart utf-8
2个回答
0
投票

试试这个代码

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');
      }
      
    }

0
投票

后端解决方案

我遇到了同样的问题,并通过在应用程序的后端设置字符编码解决了它。

这可以通过附加

Content-Type
标题来完成,如下所示:

Content-Type: application/json;charset=UTF-8

根据您的框架/实现,有不同的方法可以实现这一目标。

不幸的是,这个答案本身并不适合 Flutter。

© www.soinside.com 2019 - 2024. All rights reserved.