Flutter数据规范化插件normalizr的使用
Flutter数据规范化插件normalizr的使用
关于
许多API(公开或私有的)返回的数据是JSON格式,并且这些JSON数据通常是深度嵌套的对象。在这样的结构中使用数据往往非常困难。
Normalizr 是一个小型但功能强大的工具,用于根据模式定义将JSON数据规范化为具有ID的嵌套实体,并将它们聚集在字典中。
链接
使用
示例输入JSON
{
"id": "123",
"author": {"id": "1", "name": "Paul"},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {"id": "2", "name": "Nicole"}
}
]
}
规范化
import 'package:normalizr/normalizr.dart';
import 'dart:convert';
// 定义用户模式
final user = Entity('users');
// 定义评论模式
final comment = Entity('comments', {
'commenter': Ref('users'),
});
// 定义文章模式
final article = Entity('articles', {
'author': Ref('users'),
'comments': Ref.list('comments'),
});
void main() {
// 设置
normalizr.addAll([user, comment, article]);
// 输入数据
final data = {
"id": "123",
"author": {"id": "1", "name": "Paul"},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {"id": "2", "name": "Nicole"}
}
]
};
// 规范化数据
final normalizedData = normalize(data, article);
// 输出
final encoder = JsonEncoder.withIndent(' ');
String prettyJson = encoder.convert(normalizedData);
print(prettyJson);
}
输出结果
{
"result": "123",
"type": "articles",
"entities": {
"users": {
"1": {
"id": "1",
"name": "Paul"
},
"2": {
"id": "2",
"name": "Nicole"
}
},
"comments": {
"324": {
"id": "324",
"commenter": "2"
}
},
"articles": {
"123": {
"id": "123",
"author": "1",
"title": "My awesome blog post",
"comments": [
"324"
]
}
}
}
}
更多关于Flutter数据规范化插件normalizr的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复