Parsing JSON

This article shows how to parse JSON into object.

JSON

Assuming we get JSON result below from web api.
A list of entities, each entity contains a list of groups.

{
  "entities": [
    {
      "id": "1",
      "name": "Entity 1",
      "groups": [
        {
          "id": "1",
          "name": "Group 1",
          "isSubscribed": false
        },
        {
          "id": "2",
          "name": "Group 2",
          "isSubscribed": true
        }
      ]
    },
    {
      "id": "2",
      "name": "Entity 2",
      "groups": [
        {
          "id": "3",
          "name": "Group 3",
          "isSubscribed": false
        },
        {
          "id": "4",
          "name": "Group 4",
          "isSubscribed": true
        }
      ]
    }
  ]
}

Object and parsing method

class MyGroup {
  List<MyGroupEntity> entities;

  MyGroup({
    this.entities,
  });

  factory MyGroup.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['entities'] as List;
    List<MyGroupEntity> entitiesList =
        list.map((i) => MyGroupEntity.fromJson(i)).toList();
    return new MyGroup(
      entities: entitiesList,
    );
  }
}

class MyGroupEntity {
  String id, name;
  List<MyGroupEntityGroup> groups;

  MyGroupEntity({this.id, this.name, this.groups});

  factory MyGroupEntity.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['groups'] as List;
    List<MyGroupEntityGroup> groupsList =
        list.map((i) => MyGroupEntityGroup.fromJson(i)).toList();
    return new MyGroupEntity(
      id: parsedJson['id'],
      name: parsedJson['name'],
      groups: groupsList,
    );
  }
}

class MyGroupEntityGroup {
  String id, name;
  bool issubscribed;

  MyGroupEntityGroup({this.id, this.name, this.issubscribed});

  factory MyGroupEntityGroup.fromJson(Map<String, dynamic> parsedJson) {
    return new MyGroupEntityGroup(
      id: parsedJson['id'],
      name: parsedJson['name'],
      issubscribed: parsedJson['isSubscribed'],
    );
  }
}

Call parsing method

Map decoded = json.decode(jsonString);

MyGroup myGroup = MyGroup.fromJson(decoded);