You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter解析Azure Blob存储JSON报错:期望Map却获List,求解决

问题

已成功从Azure Blob存储读取JSON数据,现需在Flutter(Dart语言)中解析并打印该数据,使用的代码如下:

Future<void> main() async {
 String sasUrl = 'blob file url sas token';
try {
  // Send HTTP GET request to the SAS URL
  final response = await http.get(Uri.parse(sasUrl));

  if (response.statusCode == 200) {
  // Parse response body as bytes
  String responsebody  = response.body;

  List<String> lines = LineSplitter().convert(responsebody) ;
  
  lines.forEach((line) {
    Map<String, dynamic> jsonData = json.decode(line);
    print(jsonData);
    jsonData.forEach((key, value) {
      print('$key: $value');
    });
  });

  // Handle the data as needed
} else {
  print('Failed to fetch data: ${response.statusCode}');
}
} catch (e) {
  print('Error fetching data: $e');
}
}

运行后出现错误:

Error fetching data: Expected a value of type 'Map<String, dynamic>', but got one of type 'List'

尝试过类型转换但无效,求解决方法。

解决方法

错误核心是你解析的某一行JSON数据不是Map<String, dynamic>类型,而是List类型,按以下步骤修复:

  • 先确认每行JSON的实际结构
    在解析前打印原始行内容,明确该行是数组还是对象,再针对性处理:

    lines.forEach((line) {
      print('原始行内容:$line');
      dynamic parsedData = json.decode(line);
      if (parsedData is List) {
        // 处理数组类型的行
        print('当前行是数组:$parsedData');
        parsedData.forEach((item) {
          if (item is Map<String, dynamic>) {
            item.forEach((key, value) {
              print('$key: $value');
            });
          }
        });
      } else if (parsedData is Map<String, dynamic>) {
        // 原逻辑处理对象类型的行
        print(parsedData);
        parsedData.forEach((key, value) {
          print('$key: $value');
        });
      } else {
        print('非对象/数组类型数据:$parsedData');
      }
    });
    
  • 检查Azure Blob中的JSON格式
    确认Blob内的JSON每行结构是否统一,有可能某一行是数组格式(比如[{"key":"value"},...]),直接转Map就会触发类型错误。

  • 统一调整解析类型
    如果所有行都应该是数组,直接将解析类型改为List:

    List<dynamic> jsonData = json.decode(line);
    

内容的提问来源于stack exchange,提问作者sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:52:38