Reputation: 59
I have a JSON structure that consists of categories. These categories can have different amount of nodes and these nodes have a map of nodes inside of them aswell. The example structure of this JSON looks like this:
[
{
"id":"category1",
"name":"Piłka nożna",
"nodes":[
{
"id":"node1",
"name":"Bayern Monachium",
"parentId":"category1",
"nodes": [
{
"id":"node12",
"name":"Robert Lewandowski",
"parentId":"node1",
"nodes": []
},
{
"id":"node13",
"name":"Thomas Mueller",
"parentId":"node1",
"nodes": []
}
]
},
{
"id":"node2",
"name":"Hertha Berlin",
"parentId":"category1",
"nodes": []
},
{
"id":"node5",
"name":"Werder Brema",
"parentId":"category1",
"nodes": []
}
]
},
{
"id":"category2",
"name":"Koszykówka",
"nodes": []
}
]
I have written classes which would allow to represent this JSON with objects:
class Category {
String id;
String name;
Map<String,Node> nodes;
Category(String id, String name, Map<String,Node> nodes) {
this.id = id;
this.name = name;
this.nodes = nodes;
}
}
class Node {
String id;
String name;
String parentId;
Map<String, Node> nodes;
Node(String id, String name, String parentId, Map<String, Node> nodes) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.nodes = nodes;
}
}
What would be the proper way to map the JSON of this type into the instances of these classes?
Upvotes: 0
Views: 187
Reputation: 503
An option is to loop over nodes List and create a Node class from each one of them. Here, I implemented a fromJson nammed constructor but dart packages exist to ease the process of deserialization such as json_serializable.
class Node {
String id;
String name;
String parentId;
List<Node> nodes;
Node.fromJson(Map<String, dynamic> json) {
this.id = json["id"];
this.name = json["name"];
this.parentId = json["parentId"];
this.nodes = json["nodes"].map<Node>((node) {
return Node.fromJson(node);
}).toList();
}
}
class Category {
String id;
String name;
List<Node> nodes;
Category.fromJson(Map<String, dynamic> json) {
this.id = json["id"];
this.name = json["name"];
this.nodes = json["nodes"].map<Node>((node) {
return Node.fromJson(node);
}).toList();
}
}
final categories = [json list].map<Category>((category) => Category.fromJson(category)).toList();
Upvotes: 1