I am trying to get the JSON response from the server and output it to the console.

Future<String> login() async {
    var response = await http.get(
        Uri.encodeFull("https://etrans.herokuapp.com/test/2"),
        headers: {"Accept": "application/json"});

    this.setState(() {
      data = json.decode(response.body);
    });


    print(data[0].name);
    return "Success!";
  }

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List

What could be the reason?

推荐答案

以下是可能出错的两种常见方式:

  1. 如果您的响应是如下所示的json数组

    [
        {
          key1: value1,
          key2: value2,
          key3: value3,
        },
        {
          key1: value1,
          key2: value2,
          key3: value3,
        },
    
        .....
    ] 
    

    Then, we use data[0]["name"], not data[0].name Unless we cast to an object that has the name property, we cannot use data[0].name

    We cast like this data = json.decode(response.body).cast<ObjectName>();

    ObjectName can be whatever object you want (Inbuilt or Custom). But make sure it has the name property

  2. 如果您的响应是JSON对象,比如

    {
        dataKey: [
          {
            key1: value1,
            key2: value2,
            key3: value3,
          } 
        ] 
    }
    

    Then json.decode will return a Map, not a List

    Map<String, dynamic> map = json.decode(response.body);
    List<dynamic> data = map["dataKey"];
    print(data[0]["name"]);
    

Json相关问答推荐

从Json响应中为需要每个值的Post请求提取多个值

如何创建生成两个不同对象的JSON数组的SQL查询?

修改Deneb图表中工具提示的字体大小

如何判断响应数组是否存在以及S是否有其他内容...?

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

在 SQL 存储过程中使用参数 Select 值

从 JSON 响应中获取最新版本发布字段

如何将从嵌套 Select 返回的空值转换为空数组?

将哈希表转换为 json 后,Powershell 缺少数组

如何在 Django 的模板语言中获取 json 键和值?

在PowerShell中按时间戳过滤JSON

从 JSON 对象中删除键值对

现代浏览器一次可以处理多少个 HTML 元素?

将带有数据和文件的 JSON 发布到 Web Api - jQuery / MVC

嵌套 JSON:如何向对象添加(推送)新项目?

将 javascript 对象或数组转换为 json 以获取 ajax 数据

如何转换为 D3 的 JSON 格式?

Django:TypeError:[] 不是 JSON 可序列化的为什么?

如何遍历 JSON 中的条目?