【问题标题】:How to convert Map Data to Custom List (Nested , Recursive)?如何将地图数据转换为自定义列表(嵌套、递归)?
【发布时间】:2020-05-28 08:26:51
【问题描述】:

我想转换 ....
From: Convert Map(String, Dynamic)
To: Entry(String title, List children)

地图对象:

Map<String, dynamic> mapData = {
  "A": {
        "B": {
               "C": 
                  {
                    "data1": "some data1",
                    "data2": "some data2",
                    "data3": "some data3",
                    "data4": "some data 4"  
                  }
             }
  },
  .......  
};
]

data = generateRecursiveList(mapData);

// 我想要输出对象的数据

List<Entry> finalList = new List<Entry>();


List<Entry> generateRecursiveList(Map group){
var keylist = group.keys.toList();
var valueslist = group.values.toList();

for(int i=0; i<keylist.length;i++){
  Entry entry = new Entry();
  entry.title = keylist[i].toString();
  List<Entry> childEntries = new List<Entry>(); 
  for(int j=0; i<valueslist[j].length;j++){
     if(valueslist[j] is Map){
       childEntries.add(generateRecursiveList(valueslist[j]));  // Recursive calling the same function to get the children
    // I am not sure how i will get this children now
    entry.children = childEntries;
     }    
  }
// This is also I am not sure how to add the entries
   finalEntries.add(entry);
}
}

输出对象:

final List<Entry> data = <Entry>[
  Entry( 'A', <Entry>[
    Entry( 'B',<Entry>[
         Entry( 'C',<Entry>[
                     Entry( 'some data 1'), 
                     Entry( 'some data 2'),
                     Entry( 'some data 3'),
                     Entry( 'some data 4')
                    ])
          ])
    ]), 
  ....
];

我尝试编写递归函数,但无法将这些嵌套映射转换为列表。

【问题讨论】:

  • 你的输出有什么问题?

标签: flutter dart


【解决方案1】:

你可以这样做:

class Entry {
  Entry({this.title, this.children});

  String title;
  List<Entry> children;
}

List<Entry> fromJson(Map<String, dynamic> json) {
  final keys = json.keys.toList();
  final res = List<Entry>();
  for (final key in keys) {
    final entry = Entry(title: key, children: fromJson(json[key]));
    res.add(entry);
  }
  return res;
}

编辑:由于Dart 2.3,加上for collectionsfromJson也可以这样写:

List<Entry> fromJson(Map<String, dynamic> json) {
  return [
    for (final key in json.keys)
      Entry(title: key, children: fromJson(json[key]))
  ];
}

【讨论】:

  • 感谢 Augustin R,您的代码对我有很大帮助,而且很有效。每当它上线时,我一定会在 App Credits 中给你信用:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多