I am trying to convert Map<DateTime,List> into json with following code:
String ecoded = json.encode({
DateTime.now(): ["Sample data", 3,true,"Example", 2],
});
But compiler give following error:
E/flutter (11773): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled
Exception: Converting object to an encodable object failed: _LinkedHashMap len:1
E/flutter (11773): #0 _JsonStringifier.writeObject
(dart:convert/json.dart:688:7)
E/flutter (11773): #1 _JsonStringStringifier.printOn
(dart:convert/json.dart:877:17)
E/flutter (11773): #2 _JsonStringStringifier.stringify
(dart:convert/json.dart:862:5)
E/flutter (11773): #3 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter (11773): #4 JsonCodec.encode (dart:convert/json.dart:172:45)
I converted many times Map into json but in all cases Map was something like that:
Map<String,dynamic>
This error is occurring because there is List
If anyone know how to convert Map<DateTime,List> into json then Answer this question.
Thanks
CodePudding user response:
Json only supports Strings
as keys. So if you want to use DateTimes
as keys you have to manually convert it first:
String ecoded = json.encode({
DateTime.now().toString(): ["Sample data", 3,true,"Example", 2],
});
or
Map<String, dynamic> result = datetimeMap.map((k, v) => MapEntry('$k', v))
CodePudding user response:
In dart programming, json.encode(DateTime.Now()) which is not possible. You need to convert by using Iso8601String()
or toString()
String ecoded = json.encode({
DateTime.now().toIso8610String(): ["Sample data", 3,true,"Example", 2],
});