Flutter如何从JSON数据创建列表

时间:2020-06-29 15:54:30

标签: flutter dart

下面是一个在线示例,我有以下代码: 将一些json数据放入列表中,但问题在于数据是映射字符串形式

 Future<List<Phone>> getData() async {
    http.Response response = await http.get(
        Uri.encodeFull("http://chicken20.pythonanywhere.com/user"),
        headers: {"Accept": "application/json"});
    /*setState(() {
      phone = json.decode(response.body);
      print (phone[0]);
    });*/

    List<Phone> users = (json.decode(response.body) as List)
        .map((data) =>Phone.fromJson(data))
        .toList();
return users;
  }

我的json文件

{"user":[{"email":"iot3@iot.com","id":1,"password":"1234","username":"med"},{"email":"firas.slimene@gmail.com","id":2,"password":"123456789","username":"firas_96"},{"email":"ahmedmattousii77@gmail.com","id":3,"password":"07495074","username":"ahmed"},{"email":"feharou@gmail.com","id":6,"password":"1234","username":"wajdi hassyaoui"},{"email":"matt@gmail.com","id":7,"password":"1234","username":"matt"}]}

错误

 [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

模型 电话类别{ 用户用户;

  Phone({this.user});

  Phone.fromJson(Map<String, dynamic> json) {
    user = json['user'] != null ? new User.fromJson(json['user']) : null;
   
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.user != null) {
      data['user'] = this.user.toJson();
     


    }
    return data;
  }
}

class User{
  String email;
  String password;

  User({this.email,this.password});

  User.fromJson(Map<String, dynamic> json) {
    email = json['email'];
    password=json['password'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['email'] = this.email;
    data['password'] = this.password;
    return data;
  }
}

我需要一些帮助,谢谢

1 个答案:

答案 0 :(得分:0)

用户列表显示在您获得的json的“用户”对象中

Future<List<Phone>> getData() async {
    http.Response response = await http.get(
        Uri.encodeFull("http://chicken20.pythonanywhere.com/user"),
        headers: {"Accept": "application/json"});
    /*setState(() {
      phone = json.decode(response.body);
      print (phone[0]);
    });*/

    List<Phone> users = (json.decode(response.body)['user'] as List)
        .map((data) =>Phone.fromJson(data))
        .toList();
    return users;
}