Search code examples
jsonflutterdartjson-deserialization

Flutter Dart deserialize a json with dynamic key but structured values into Map<String, ModelClass>


Is it possible to deserialize a json with dynamic key but structured values into Map in flutter dart.

I am having a json like

{
   "data" : {
            "apple":{"qty":5, "price":100},
            "orange":{"qty":2, "price":40},
           }
}

And I want this to deserialize in flutter/dart to a model class below

class Data {
    Map<String, Item> itemMap;

    factory Data.fromJson(Map<String,dynamic> json) {
        itemMap : json["data"]; //How to parse.
    }
}

class Item {
   int qty;
   int price;
}

I have read through a medium blog and even this also not covering the Map part.


Solution

  • I found a way to achieve it. We can convert the Map from one type to another.

    class Data {
        Map<String, Item> itemMap;
    
        factory Data.fromJson(Map<String,dynamic> json) {
            itemMap : getMapDataFrom(json["data"]); //How to parse.
        }
    
        static Map<String, Item> getFruitItemMap(Map<String, dynamic> map) {
           final Map<String, Item> fruitItemMap = HashMap();
           map.forEach((name, value) {
               bitItemLites[name] = Item.fromJson(value, name);
           });
    
           return bitItemLites;
        }
    }
    
    class Item {
       int qty;
       int price;
    
       factory Item.fromJson(Map<String,dynamic> json) {
          return Item(json['qty'], json['price']);
       }
    }