有没有办法序列化 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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...