Flutter Dart将具有动态键但结构化值的json反序列化为Map< String,ModelClass> [英] Flutter Dart deserialize a json with dynamic key but structured values into Map<String, ModelClass>

查看:116
本文介绍了Flutter Dart将具有动态键但结构化值的json反序列化为Map< String,ModelClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将带有动态键但结构化值的json反序列化为Flutter dart中的Map.

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

我有一个像

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

我希望这可以在 flutter/dart 中反序列化到下面的模型类

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;
}

我已经阅读了中型博客甚至也没有涵盖Map部分.

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

推荐答案

我找到了一种方法来实现它.我们可以将地图从一种类型转换为另一种类型.

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

这篇关于Flutter Dart将具有动态键但结构化值的json反序列化为Map&lt; String,ModelClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆