I'm trying to parse my JSON into Data class object. I did some research and did come upon some helpful articles but am still running into errors.
The response I get from the backend:
"entrances": {
"options": {
"mainEntrance": {
"text": "Enter through the main doors"
},
"backEntrance": {
"text": "Enter through the back doors"
},
"sideEntrance": {
"text": "Enter through the side doors"
}
},
"footer": "Text goes here"
},
"status": {
"state": "open"
}
}
Model
class MyClass {
String id;
Options option;
MyClass({this.id, this.option});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
option = json['option'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['option'] = this.option;
return data;
}
}
class Options {
String name;
String text;
Options({this.name, this.text});
Options.fromJson(Map<String, dynamic> json) {
name = json['name'];
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['text'] = this.text;
return data;
}
}
Decoding the response and mapping
setState(() {
Map myMap = json.decode(response.body);
List<MyClass> myClassList = new List<MyClass>();
myMap['entrances'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((MyClass) {
print(MyClass.id);
print(MyClass.option.name);
print("--------------------\n");
});
});
I get this error:
Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method '[]='.
Tried calling: []=("id", "footer")
What am I doing wrong? Are there better approaches out there?