我有一个API,返回带有动态键的JSON,即每个GET
请求的键值都会更改。
例如:这是JSON的格式。
我在Dart中有一个书籍模型,
class Book {
String id = "";
String title = "";
Book();
Book.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
}
static List<Book> listFromJson(List<dynamic> json) {
return json.map((val) => Book.fromJson(val)).toList();
}
}
以及JSON响应,
{
"Recommended For You" : [
{
"id" : "001",
"title" : "title001"
},
...
],
"Thrillers" : [
{
"id" : "005",
"title" : "title005"
},
...
]
}
如何将其解析为书籍列表,根据流派分类,考虑到流派(如
Thrillers
)可能会更改(即对于每个用户都是动态的,可能会更改)?
编辑 1
Thrillers
和 Recommended For You
不是固定的,有时可能会更改为 Horror
和 Romantic
或其他内容。它是动态的
编辑 2:解决方案
感谢 @lrn 的解决方案,我想出了一个新的类
class Recommendations {
String recommendationType;
List<Book> recommendations;
@override
String toString() {
return 'Recomendations[title: $recommendationType]';
}
Recommendations.fromJson(MapEntry<String, dynamic> json) {
if (json == null) return;
this.recommendationType = json.key;
this.recommendations = Book.listFromJson(json.value);
}
static List<Recommendations> listFromJson(Map<String, dynamic> json) {
return json == null
? List<Recommendations>.empty()
: json.entries
.map((value) => new Recommendations.fromJson(value))
.toList();
}
}