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

从Web JSON提取locations列表时遇类型转换错误,求解决方案

问题解决:提取JSON中所有location值并避免类型转换错误

首先,你提供的原始JSON存在语法错误:

  • 最后一个location字段末尾多了逗号
  • stops数组的最后一个元素末尾多了逗号
  • 顶级对象末尾多了逗号

这些错误会导致JSON解析失败,先修正为合法JSON:

{
    "trType": "TYPEX",
    "stops": [
        {
            "location": "STREET 1"
        },
        {
            "location": "STREET 2"
        },
        {
            "location": "STREET 3"
        }
    ]
}

错误原因

你遇到的String' is not a subtype of type 'List<dynamic>'错误,本质是将字符串类型的字段强制转换成了列表,常见场景:

  1. 解析时误把trType这类字符串字段当成stops列表处理
  2. Web返回的JSON中stops字段实际是字符串而非列表(和你提供的示例不符,但需排查)
  3. JSON解析失败后,错误处理不当导致类型混乱

正确实现(以Dart为例)

import 'dart:convert';

void main() {
  // 模拟Web获取的合法JSON字符串
  final jsonStr = '''
  {
      "trType": "TYPEX",
      "stops": [
          {
              "location": "STREET 1"
          },
          {
              "location": "STREET 2"
          },
          {
              "location": "STREET 3"
          }
      ]
  }
  ''';

  // 解析JSON为Map
  final data = jsonDecode(jsonStr) as Map<String, dynamic>;

  // 安全提取stops列表,先判断类型避免转换错误
  if (data['stops'] is List) {
    final stopsList = data['stops'] as List<dynamic>;
    // 提取所有location值到列表
    final locations = stopsList.map((stop) => stop['location'] as String).toList();

    // 遍历执行操作(示例:打印)
    for (final loc in locations) {
      print(loc);
    }
  } else {
    print('错误:stops字段不是列表类型');
  }
}

关键注意事项

  • 始终先验证字段类型:用is判断data['stops']是否为List,再做类型转换
  • 确保Web返回的JSON格式合法,避免多余逗号、字段类型不符等问题
  • 如果使用强类型模型(比如json_serializable),更能提前规避类型错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:57:36