Flutter 将 json 响应加载到 List

Posted

技术标签:

【中文标题】Flutter 将 json 响应加载到 List【英文标题】:Flutter load json response to List 【发布时间】:2021-09-30 11:29:42 【问题描述】:

此 json 响应适用于以下列表。

["id":"1","ename":"KING","sal":"5000"............

List<Emp> emp= (json.decode(response.body) as List)
        .map((data) => Emp.fromJson(data))
        .toList();

但是在启动 json 时如何在列表中加载数据留在 items

"items":["id":1,"ename":"KING","sal":5000............

【问题讨论】:

【参考方案1】:

使用json.decode(response.body)['items'] 代替json.decode(response.body)

一个例子:

import 'dart:convert';

void main() 
  
  // sample body.response

  final j = '''
  "items": [
  "id":"1","ename":"KING","sal":"5000",
  "id":"2","ename":"KING","sal":"5000"
  ]
  ''';

  List<Emp> emp = (json.decode(j)['items'] as List)
      .map((data) => Emp.fromJson(data))
      .toList();

  print(emp);


class Emp 
  String id;
  String ename;
  String sal;

  Emp(this.id, this.ename, this.sal);

  Emp.fromJson(Map<String, dynamic> json) 
    id = json['id'];
    ename = json['ename'];
    sal = json['sal'];
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['ename'] = this.ename;
    data['sal'] = this.sal;
    return data;
  

【讨论】:

【参考方案2】:
List<Emp> emp= (json.decode(response.body)["items"] as List)
        .map((data) => Emp.fromJson(data))
        .toList();

【讨论】:

以上是关于Flutter 将 json 响应加载到 List的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:JSON无键数组到列表

解析json数组响应/颤动

将json响应添加到flutter中的列表

如何将 JSON 资产加载到 Flutter 应用程序中?

json - 如何在 flutter 中的List String中加入2 json值?

尝试获取 json 响应时出错 [Flutter]