使用Dart中的JsonObject库解析JSON列表

时间:2013-01-22 15:24:54

标签: json dart

我正在尝试在JsonOject库的帮助下解析一些JSON。我遇到以下异常:

 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);

我在这里做错了什么?

1 个答案:

答案 0 :(得分:6)

我已更新我的JsonObject github repo以修复此错误。我还添加了passing unit test来重现这一点。

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

现在可以使用以下代码:

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());
  }
}