30

How to convert DateTime object to json? It throws Converting object to an encodable object failed., so is this a bug or it's just dart haven't yet support it? If you guys know some workaround please let me know.

Patrice Chalin
  • 14,022
  • 7
  • 30
  • 43
Faris Nasution
  • 2,910
  • 5
  • 21
  • 26

4 Answers4

41

Rather than using a wrapper, you can also create your own custom encoder passing the toEncodable argument.

import 'dart:convert' show JSON;

void main() {
  var dt = new DateTime.now();
  var str = JSON.encode(dt, toEncodable: myEncode);
  print(str);
}

dynamic myEncode(dynamic item) {
  if(item is DateTime) {
    return item.toIso8601String();
  }
  return item;
}
Matt B
  • 5,802
  • 1
  • 18
  • 26
3

you are encoding object(DateTime) into other encodable object JSON.encode(DateTime.Now()) which is not possible in dart programming.

So, convert it to dart supported Date to String conversion that is : add : .toIso8601String() at the end

JSON.encode(DateTime.Now().toIso8601String()),this resolves your error. // i am taking DateTime.Now() just for example.

akash maurya
  • 410
  • 5
  • 11
2

first: JSON does not support date/time encoding.. this is usually done by convention depending on the other party - usually a string representation (e.g. ISO8601 but Microsoft's ASP.NET uses a custom format).

second: How to convert an object containing DateTime fields to JSON in Dart?
(In short: Runtime does not serialise DateTime. You'll need to create a wrapper with custom serialisation logic.)

Community
  • 1
  • 1
Martin Ullrich
  • 86,695
  • 21
  • 239
  • 204
0

You could also just convert your map in Dart.

Map<String, dynamic> encodeMap(Map<String, dynamic> map) {
  map.forEach((key, value) {
    if (value is DateTime) {
      map[key] = value.toString();
    }
  });
  return map;
}

Usage: var _map = encodeMap(_data);

Rody Davis
  • 1,340
  • 11
  • 20