flutter dart json decode encode
Very Important!
{"107年工作":{"zhangqi":[{"name":"王大明1"},{"name":"孫小明1"}],"chaojiangeren":[{"name":"nnn1","addr":"aaa1"},{"name":"nnn2","addr":"aaa2"}]},"108年法會":{"zhangqi":[{"name":"王大明1"},{"name":"孫小明1"}]}}
zhangqi : [ …. ]
chaojiangeren: [ …. ]
zhangqi : [ {….}, {….} ]
chaojiangeren: [ {….}, {….} ]
Can’t have \' or \"
If have this, json.decode can’t List
List => List
List => List
List<ItemName> zhangqi = List<ItemName>();
zhangqi.add(new ItemName(name:"王大明1"));
zhangqi.add(new ItemName(name:"孫小明1"));
List<ItemNameAddr> chaojiangeren = List<ItemNameAddr>();
chaojiangeren.add(new ItemNameAddr(name:"nnn1", addr:"aaa1"));
chaojiangeren.add(new ItemNameAddr(name:"nnn2", addr:"aaa2"));
class ItemName {
String name;
ItemName({ this.name }) ;
ItemName.fromJson(Map<String, dynamic> json) : name = json['name'];
Map toJson() => {"name": name }; //給json.encode使用,沒有的話,會錯誤
}
class ItemNameAddr {
String name;
String addr;
ItemNameAddr({ this.name, this.addr }) ;
ItemNameAddr.fromJson(Map<String, dynamic> json) : name = json['name'], addr = json['addr'];
Map toJson() => {"name": name, "addr": addr}; //給json.encode使用,沒有的話,會錯誤
}
Future<List<ItemName>> getListItemName(List maps) async {
return new List<ItemName>.generate(maps.length, (i) {
return ItemName(
name: maps[i]['name'],
);
});
}
Future<List<ItemNameAddr>> getListItemNameAddr(List maps) async {
return new List<ItemNameAddr>.generate(maps.length, (i) {
return ItemNameAddr(
name: maps[i]['name'],
addr: maps[i]['addr'],
);
});
}