如何解决有没有办法序列化 json 响应来自 .net API以用 dart 中的完整对象替换列表中的 $ref 对象?
我有一个 API,它返回的响应类似于 this post 中所示的响应。
我的回复是列表中的对象只包含一个 $ref 变量,该变量指向列表中某处具有相关 $id 的子对象。
我尝试了以下方法,但它不适用于更大更复杂的响应,而且我怀疑它会大大增加计算时间:
Future<List<Category>> getCategories() async {
String token = await FlutterSession().get("accessToken");
final response =
await http.get('$url/api/categories/',headers: <String,String>{
'Content-Type': 'application/x-www-form-urlencoded','Authorization': 'Bearer ' + token,});
if (response.statusCode == 200) {
categories = categoriesFromJson(response.body);
var incompleteCats = categories.where((c) => c.id == null);
incompleteCats.forEach((ic) {
categories.remove(ic);
var completeCat =
categories.where((s) => s.parent?.$id == ic.$ref).first.parent;
categories.add(completeCat);
});
return categories;
} else {
throw Exception('Failed to get categories');
}
}
API 响应示例
[
{
"$id": "3","Parent": {
"$id": "4","Parent": {
"$ref": "1"
},"CategoryName": "General","Description": "Test","ParentCategoryId": 45,"SortOrder": 2,"Id": 49,"IsDeleted": false,"CreatedDate": "2009-11-29T00:00:00","CreatedByUserId": 1,"UpdatedDate": "1900-01-01T00:00:00","UpdatedByUserId": null,"State": 0
},"CategoryName": "Country","ParentCategoryId": 49,"SortOrder": 3,"Id": 47,"CreatedDate": "2019-11-29T00:00:00","State": 0
},{
"$id": "16","Parent": {
"$ref": "4"
},"CategoryName": "Other","Description": "Other","SortOrder": 7,"Id": 61,"CreatedDate": "2020-06-05T09:13:50.863","UpdatedDate": "2020-06-05T09:13:50.863","UpdatedByUserId": 1,{
"$ref": "4"
},
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。