Dart将JSON对象数组转换为对象列表

时间:2020-10-09 05:07:52

标签: json flutter dart

我有这样的国家json对象数组

[{"id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg"},
        {"id":8,"name":"Albania","alpha2":"al","alpha3":"alb"},
        {"id":12,"name":"Algeria","alpha2":"dz","alpha3":"dza"},..

我已经把他们放在这样的地图上

Map<String, dynamic> jsonMap;
jsonMap = json.decode(jsonString);

在这之后,我得到了这样的数据

[{id: 4, name: Afghanistan, alpha2: af, alpha3: afg}, {id: 8, name: Albania, alpha2: al, alpha3: alb}, ...

我想要做的是从中创建县对象列表

Country
{
int id;
String name;
String alpha2;
String alpha3;
}

任何人都可以解释如何进行此转换吗?

2 个答案:

答案 0 :(得分:1)

做到这一点的最好方法是从中制作出PODO,

class Country {
  int id;
  String name;
  String alpha2;
  String alpha3;

  Country({this.id, this.name, this.alpha2, this.alpha3});

  Country.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    alpha2 = json['alpha2'];
    alpha3 = json['alpha3'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['alpha2'] = this.alpha2;
    data['alpha3'] = this.alpha3;
    return data;
  }
}

现在使用此方法,您可以访问fromJson方法,也可以使用toJson方法。

答案 1 :(得分:0)

我使用这种简单的方法:

List<TestModel> myTestModel;
var response = await http.get("myTestUrl");

myTestModel=(json.decode(response.body) as List).map((i) =>
              TestModel.fromJson(i)).toList();

该链接非常有用: json_serializable