简体   繁体   中英

Dart convert Map<dynamic, dynamic> to Map<String, List<String>>

How to convert such a Map :

Map<dynamic, dynamic> a = {2022-04-10: [8:00, 15:00]}; //No quotes

To obtain:

Map<String, List<String>> b = {"2022-04-10": ["8:00", "15:00"]};

I tried to do so, but it doesn't work for me. There is no error, but if you call print, nothing happens:

String str = '{2022-04-10: [8:00, 15:00]}';
final Map<dynamic, dynamic> dynamicMapFromJson = json.decode(str);
Map<String, List<String>> schedule = dynamicMapFromJson.cast<String, List<String>>();

I am teaching this Map from Firebase:

在此处输入图像描述

await FirebaseFirestore.instance
        .collection('call')
        .get()
        .then((QuerySnapshot querySnapshot) {
      for (var doc in querySnapshot.docs) {
        Map<String, List<String>> _schedule = doc.get('schedule');
      }
    });

Your map is

Map<dynamic, dynamic> a = {"2022-04-10": ["8:00", "15:00"]};

you can convert it by two ways

Map<dynamic, dynamic> a = {"2022-04-10": ["8:00", "15:00"]};
Map<String, List<String>> converted = {};

// 1st way:
for (var item in a.keys)
  converted[item.toString()] = List<String>.from(a[item]);
 
// 2nd way:
for (var item in a.keys)
{
  List<String> _new = [];
  for (var newItem in List.from(a[item]))
     _new.add(newItem.toString());
  converted[item.toString()] = _new;
}

you can use the magic of regex "it's not really perfect expression" but it's working fine with your case here you can matches date yyyy-mm-dd and hh: mm then replace with quoted ones

String str = '{2022-04-10: [8:00, 15:00]}';

 var stringify =  str.replaceAllMapped(RegExp("([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{0,2}:[0-9]{0,2})"), (match) => "\"${match.group(0)}\""); 
 //This step just for replace ":" with normal :
 stringify = stringify.replaceAll("\":\"",":");
 print("value:  $stringify");

  
 final Map dynamicMapFromJson = json.decode(stringify);
 print(dynamicMapFromJson);

Try the code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM