Parsing JSON with Dart

At the moment, JSON.parse only returns Lists (array), Maps, String, num, bool, and null (api ref).

I suspect that until reflection makes it way into the language, it won't be able to re-construct objects based upon the keys found in json.

You could, however, create a constructor in your MyJsonObject which took a string, called JSON.parse internally, and assigned the various values.

Something like this works in the dart editor:

#import("dart:json");
class Level2 {
   var type;
   var entry;
}

class Level1 {
   var name;
   var level2;        
}

class MyJSONObject {
  Level1 level1;


  MyJSONObject(jsonString) {
     Map map = JSON.parse(jsonString);

     this.level1 = new Level1();
     level1.name = map['level1']['name'];
     level1.level2 = new Level2();
     level1.level2.type = map['level1']['level2']['type'];
     //etc...

  }
}

main() {
   var obj = new MyJSONObject(json);
   print(obj.level1.level2.type);

}

A non trivial version would needs some loops and possible recursion if you had deeper nested levels.

Update: I've hacked together a non-trivial version (inspired by the post below), it's up on github (also taking Seth's comments re the constructor):


Chris is completely right. I will only add that the JSON parser could be modified to return a little richer object (something like JsonMap instead of pure Map) that could allow jsonObj.property by implementing noSuchMethod. That would obviously perform worse than jsonObj['property'].

Tags:

Json

Dart