I need to create a dart Model class for this complex json .Please any one help
{
"status": "1",
"list": {
"4": [
{
"id": "1289",
"t": "Mutton biriyani",
"p": "21",
"i": "1289_5305.jpg",
"v": "0"
},
{
"id": "1288",
"t": "Chicken biriyani",
"p": "14",
"i": "1288_5339.jpg",
"v": "0"
}
]
}
}
can any one help
CodePudding user response:
you can create modal of every json using this website json-to-dart. and after making some changes the modal for your jsong would be something like this
class Modal {
String? status;
List<FoodList>? foodList;
Modal({this.status, this.foodList});
Modal.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['list']["4"] != null) {
foodList = <FoodList>[];
json['list']["4"].forEach((v) {
foodList!.add(new FoodList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.foodList != null) {
data['list']["4"] = this.foodList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class FoodList {
String? id;
String? t;
String? p;
String? i;
String? v;
FoodList({this.id, this.t, this.p, this.i, this.v});
FoodList.fromJson(Map<String, dynamic> json) {
id = json['id'];
t = json['t'];
p = json['p'];
i = json['i'];
v = json['v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['t'] = this.t;
data['p'] = this.p;
data['i'] = this.i;
data['v'] = this.v;
return data;
}
}
CodePudding user response:
Here is an example of a Dart Model class that could be used to parse the JSON you provided
class Model {
final String status;
final List list;
Model({this.status, this.list});
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
status: json['status'],
list: json['list'],
);
} }
And you can use it like this
final jsonString = '{ "status": "1", "list": { "4": [ { "id": "1289", "t": "Mutton biriyani", "p": "21", "i": "1289_5305.jpg", "v": "0" }, { "id": "1288", "t": "Chicken biriyani", "p": "14", "i": "1288_5339.jpg", "v": "0" } ] } }';
final jsonMap = jsonDecode(jsonString); final data = Model.fromJson(jsonMap);
Note that the List class is a basic type in dart, so it is not suitable for your json structure. In this case, you need to define a custom class for the "list" field.