Flutter/Dart: Converting nested objects
This is sample code for converting json formatted data (e.g. Map<String, dynamic>) into an object where the data/object contain a nested object/class. The conversion includes a nested List of objects and a Map of objects. This might be useful in cases where your data contains a complex hierarchy of data like in a report.
Paste the following code to DartPad to test:
class MyObj {
final int id;
final String name;
final bool active;
MyObj({required this.id, required this.name, required this.active});
factory MyObj.fromJson(Map<String, dynamic> json) {
return MyObj(
id: json['id'],
name: json['name'],
active: json['active'],
);
}
@override
String toString() => "<MyObj id: $id, name: $name, active: $active>";
}
class MyMainObj {
final int id;
final MyObj object;
final List<MyObj> objList;
final Map<String, MyObj> objMap;
MyMainObj({required this.id, required this.object, required this.objList, required this.objMap});
factory MyMainObj.fromJson(Map<String, dynamic> json) {
return MyMainObj(
id: json['id'],
object: MyObj.fromJson(json['object']),
objList: (json['objList'] as List).map((i) => MyObj.fromJson(i)).toList(),
objMap: (json['objMap'] as Map).map((k,v) => MapEntry(k, MyObj.fromJson(v))),
);
}
@override
String toString() => "id: $id, object: $object, objList: [$objList], objMap: {$objMap}";
}
Map<String, dynamic> data = {
'id': 1,
'object': {
'id': 1,
'name': "Test Name",
'active': true,
},
'objList': [
{
'id': 1,
'name': "Test Name",
'active': true,
},
{
'id': 2,
'name': "Test2 Name",
'active': false,
},
],
'objMap': {
'first': {
'id': 1,
'name': "Test Name",
'active': true,
},
'second': {
'id': 2,
'name': "Test2 Name",
'active': false,
},
},
};
void main() {
MyMainObj objData = MyMainObj.fromJson(data);
print("$objData");
}