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.
Serialize datetime by converting it into String You can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.
The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.
You can get the value of the date field as String by calling the getText() method of JsonParser class and then you can simply convert it into a Date object by using the parse() method of SimpleDateFormat, as you normally parse Date in Java.
JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With