Home > other >  Accessing deeply nested JSON values
Accessing deeply nested JSON values

Time:05-04

I'm receiving a JSON from an API and I'm parsing it into a Class like so :

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(),
        );
  }
}

Here is what my JSON looks like (simplified) :

{
    "_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"
 }
 }

I'm trying to access the items (offers) nested inside "restaurants" -> "offers" -> "lunch"

something like this :

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']));
  }
}

Any ideas on how I can access this json array nested inside "restaurants" -> "offers" -> "lunch" directly, without creating a a restaurant model and so on ?

  • Related