Как разобрать JSON объектов в массив списка - PullRequest
0 голосов
/ 07 августа 2020

У меня есть этот элемент, и я хочу, чтобы объекты l oop "description" и "id" были включены в список массивов;

{
  "code": 200,
  "message": "OK",
  "payload": {
    "items": [
      {
        "description": "test",
        "icon": "",
        "id": 25
      },
      {
        "description": "TEST PACKAGE",
        "icon": "",
        "id": 26
      },
      {
        "description": "TEST PACKAGE 2",
        "icon": "",
        "id": 26
      }
    ]
  }
}

Модель

Item (описание: "", id: "");

1 Ответ

1 голос
/ 07 августа 2020
  1. Класс Create Item.
class Item {
  String description;
  int id;

  Item({this.description, this.id});

}
Определить из Json конструктора для класса Item
class Item {
  String description;
  int id;

  Item({this.description, this.id});

  Item.fromJson(Map<String, dynamic> json) {
    description = json['description'];
    id = json['id'];
  }
}
  final response = await http.get("YOUR API");
  // Convert response String to Map
  final responseJson = json.decode(response.body);
  List<Item> items = List();
  if (responseJson != null && responseJson["payload"] != null) {
    Map payload = responseJson["payload"];

    if (payload["items"] != null) {
      // Convert each item from Map to Item object and add it to the items List
      payload["items"].forEach(
        (v) {
          final item = Item.fromJson(v);
          items.add(item);
        },
      );
    }
  }
...