Parsing JSON list with JsonObject library in Dart

2019-05-17 05:53发布

问题:

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'.

My code:

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

And I call it like this:

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

What am I doing wrong here?

回答1:

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

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


标签: json dart