3

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?

0tto
  • 357
  • 3
  • 14

1 Answers1

6

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());
  }
}
Chris Buckett
  • 13,738
  • 5
  • 39
  • 46
  • Is it possible to get the children parsed also so that the both the following are true? `print(list[0] is MyResult); print(list[0].Obj is MyProduct);` – 0tto Jan 22 '13 at 16:21
  • I suspect not. Everything down the tree is a JsonObject apart from the top-level class. On my todo list is a reflection based JsonObject, which I hope would cover these scenarios (but don't wait for it :) One way you might achieve that might be to use the raw JSON parser to convert the incoming JSON to a List of Maps, and then use JsonObject.fromMap() constructor to convert each Map into a JsonObject. – Chris Buckett Jan 22 '13 at 16:50
  • Ok, thanks. Just wanted to check if there was an easy way that I had missed. – 0tto Jan 22 '13 at 17:07