请求到的JSON:
{
"a": "aa",
"b": [
{
"ba": "b1111",
"bb": "b2222"
},
{
"ba": "b3333",
"bb": "b4444"
}
],
"c": {
"ca": "c111",
"cb": "c222"
}
}
对JSON进行工厂模式:
class NameModel {
String a;
List<B> b;
C c;
NameModel({this.a, this.b, this.c});
NameModel.fromJson(Map<String, dynamic> json) {
a = json['a'];
if (json['b'] != null) {
b = new List<B>();
json['b'].forEach((v) {
b.add(new B.fromJson(v));
});
}
c = json['c'] != null ? new C.fromJson(json['c']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['a'] = this.a;
if (this.b != null) {
data['b'] = this.b.map((v) => v.toJson()).toList();
}
if (this.c != null) {
data['c'] = this.c.toJson();
}
return data;
}
}
class B {
String ba;
String bb;
B({this.ba, this.bb});
B.fromJson(Map<String, dynamic> json) {
ba = json['ba'];
bb = json['bb'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ba'] = this.ba;
data['bb'] = this.bb;
return data;
}
}
class C {
String ca;
String cb;
C({this.ca, this.cb});
C.fromJson(Map<String, dynamic> json) {
ca = json['ca'];
cb = json['cb'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ca'] = this.ca;
data['cb'] = this.cb;
return data;
}
}
使用工厂模式:
var data = json.decode(snapshot.data.toString());
NameModel dataName = NameModel.fromJson(data);
setState(() {
b = dataName.b
})