我需要在 flutter 中将对象转换为数组,请找到 json
{
"billing": [
{
"id": 1,
"add_id": 23
}
],
"shipping": [
{
"id": 2,
"add_id": 345
},
{
"id": 3,
"add_id": 345
}
]
}
我需要在 flutter 中转换成数组并映射到模型,怎么做
答案 0 :(得分:0)
使用以下代码将您的 JSON 转换为类对象,fromJson 函数将 JSON 转换为对象,而 toJson 函数将对象转换为 json。
class YourClassName {
List<Billing> billing;
List<Shipping> shipping;
YourClassName({this.billing, this.shipping});
YourClassName.fromJson(Map<String, dynamic> json) {
if (json['billing'] != null) {
billing = new List<Billing>();
json['billing'].forEach((v) {
billing.add(new Billing.fromJson(v));
});
}
if (json['shipping'] != null) {
shipping = new List<Shipping>();
json['shipping'].forEach((v) {
shipping.add(new Shipping.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.billing != null) {
data['billing'] = this.billing.map((v) => v.toJson()).toList();
}
if (this.shipping != null) {
data['shipping'] = this.shipping.map((v) => v.toJson()).toList();
}
return data;
}
}
class Billing {
int id;
int addId;
Billing({this.id, this.addId});
Billing.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}
class Shipping {
int id;
int addId;
Shipping({this.id, this.addId});
Shipping.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}