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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
回答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.)