Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DateTime object to json

Tags:

json

dart

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.

like image 518
Faris Nasution Avatar asked Feb 16 '14 16:02

Faris Nasution


People also ask

How do you serialize a datetime object as JSON in Python?

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.

How do I fix the object of type datetime is not JSON serializable?

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.

How do I pass a date field in JSON?

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.

How does JSON store date time?

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.


2 Answers

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; } 
like image 52
Matt B Avatar answered Oct 07 '22 04:10

Matt B


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.

like image 20
akash maurya Avatar answered Oct 07 '22 03:10

akash maurya