在Dart中使用JsonObject库解析JSON列表 [英] Parsing JSON list with JsonObject library in Dart

查看:313
本文介绍了在Dart中使用JsonObject库解析JSON列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析一些JSON与JsonOject库的帮助。我收到以下异常:

I'm trying to parse some JSON with the help of the JsonOject library. I'm getting the following exception:

 Exception: type 'List' is not a subtype of type 'Map' of 'value'.

我的代码:

class MyList extends JsonObject implements List { 
  MyList();

  factory MyList.fromString(String jsonString) {
    return new JsonObject.fromJsonString(jsonString, new MyList());
  }
}

class MyResult extends JsonObject { 
  num Dis;
  int Flag;
  MyProduct Obj;
}

class MyProduct extends JsonObject { 
  int ID;
  String Title;
}

我这样调用:

var testJson = """
  [{"Dis":1111.1,"Flag":0,"Obj":{"ID":1,"Title":"Volvo 140"}},
  {"Dis":2222.2,"Flag":0,"Obj":{"ID":2,"Title":"Volvo 240"}}]
""";
MyList list = new MyList.fromString(testJson);
//I want to be able to do something like this.
//print(list[0].Obj.Title);

我在这里做错了什么?

推荐答案

我更新了我的 JsonObject github repo 来修复此错误。我还添加了传递单元测试,可再现此内容。

I've updated my JsonObject github repo to fix this bug. I've also added a passing unit test that reproduces this.

您需要运行 pub update 才能获取最新版本的库。

You'll need to run pub update to get the latest version of the library.

以下代码现在可以工作:

The following code now works:

import 'package:json_object/json_object.dart';

void main() {
  var testJson = """
      [{"Dis":1111.1,"Flag":0,"Obj":{"ID":1,"Title":"Volvo 140"}},
      {"Dis":2222.2,"Flag":0,"Obj":{"ID":2,"Title":"Volvo 240"}}]""";
  MyList list = new MyList.fromString(testJson);
  //I want to be able to do something like this.
  print(list[0].Obj.Title);  // <- now prints "Volvo 140"
}

class MyList extends JsonObject implements List { 
  MyList();

  factory MyList.fromString(String jsonString) {
    return new JsonObject.fromJsonString(jsonString, new MyList());
  }
}

这篇关于在Dart中使用JsonObject库解析JSON列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆