'How to convert json array to model class in flutter dart/
{
"feed": {
"entry": [
{
"im:name": {
"label": "The Rise"
},
"im:image": [
{
"label": "https://cover.jpg/55x55bb.png"
}
]
}
]
}
}
Can anybody help me how to create a dart class for this response. I tried with many online converters also. But when i implemented that code in real time showing lots of error.
Solution 1:[1]
Here:
class Model {
Feed? feed;
Model({this.feed});
Model.fromJson(Map<String, dynamic> json) {
feed = json['feed'] != null ? new Feed.fromJson(json['feed']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.feed != null) {
data['feed'] = this.feed!.toJson();
}
return data;
}
}
class Feed {
List<Entry>? entry;
Feed({this.entry});
Feed.fromJson(Map<String, dynamic> json) {
if (json['entry'] != null) {
entry = <Entry>[];
json['entry'].forEach((v) {
entry!.add(new Entry.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.entry != null) {
data['entry'] = this.entry!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Entry {
ImName? imName;
List<ImImage>? imImage;
Entry({this.imName, this.imImage});
Entry.fromJson(Map<String, dynamic> json) {
imName =
json['im:name'] != null ? new ImName.fromJson(json['im:name']) : null;
if (json['im:image'] != null) {
imImage = <ImImage>[];
json['im:image'].forEach((v) {
imImage!.add(new ImImage.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.imName != null) {
data['im:name'] = this.imName!.toJson();
}
if (this.imImage != null) {
data['im:image'] = this.imImage!.map((v) => v.toJson()).toList();
}
return data;
}
}
class ImName {
String? label;
ImName({this.label});
ImName.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['label'] = this.label;
return data;
}
}
Json To Dart does it effectively.
Solution 2:[2]
Json to and from Dart Class: Just use online dart code generation sites like below:
One correction may needed. Remove @ from @required.
I think this is the best way. build_runner is good but sometime painful. So, I adopted this method. It works best for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Josteve |
| Solution 2 | Debdutta Panda |
