访问深度嵌套的 JSON 值

Accessing deeply nested JSON values

我从 API 接收到 JSON,我正在将其解析为 Class,如下所示:

class HappyModel {
  HappyModel({
    required this.id,
    required this.name,
  });

  final String id;
  final String name;

  factory HappyModel.fromJson(Map<String, dynamic> _json) {
    return HappyModel(
        id: _json['_id'].toString(),
        name: _json['name'].toString(),
        );
  }
}

这是我的 JSON 的样子(简化):

{
    "_id":62348d85433322b995288b41,
    "date":"2022-05-02T00":"00":00.000Z,
    "name":"Happy Name",
    "restaurant":{
       "ticket":615ec9a2ec0a3a001d20abcf,
       "opened":true,
       "offers":{
          "lunch":[
             {
                "_id":4051bae6df66a612ca5d008b,
                "isOnlyForCustomer":false,
                "price":750
             },
             {
                "_id":5051bae6df66a612ca5d003a,
                "isOnlyForCustomer":false,
                "price":1000
             },
             {
                "_id":6051bae6df66a612ca5d007e,
                "isOnlyForCustomer":false,
                "price":1150
             }
          ],
          "evening":[
             {
                "_id":1041bae6df66a612ca5d00ao,
                "isOnlyForCustomer":false,
                "price":1200
             },
             {
                "_id":5051bae6df66a612ca5d000z,
                "isOnlyForCustomer":false,
                "price":750
             },
             {
                "_id":8051bae6df66a612ca5d001a,
                "isOnlyForCustomer":false,
                "price":250
             }
          ]
       },
    "something":null,
    "somethingelse":"aoaoa"
 }
 }

我正在尝试访问嵌套在 "restaurants" -> "offers" -> "lunch"

中的项目(优惠)

像这样:

class HappyModel {
  HappyModel({
    required this.id,
    required this.name,
    required this.offers,
  });

  final String id;
  final String name;
  final List<OfferModel> offers;

  factory HappyModel.fromJson(Map<String, dynamic> _json) {
    return HappyModel(
        id: _json['_id'].toString(),
        name: _json['name'].toString(),

// Here ⭐️ I'd like to access the nested json 

        offers: OfferModel.listFromJson(_json['restaurants.offers.lunch']));
  }
}

关于如何直接访问嵌套在 "restaurants" -> "offers" -> "lunch" 中的这个 json 数组,而不创建餐厅模型等,有什么想法吗?

因为我不需要其他值

访问Map的嵌套键的方法是多次调用[]运算符:

offers: OfferModel.listFromJson(_json['restaurants']['offers']['lunch'])