如何在Dart中将包含DateTime字段的对象转换为JSON? [英] How to convert an object containing DateTime fields to JSON in Dart?

查看:515
本文介绍了如何在Dart中将包含DateTime字段的对象转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将对象转换为JSON。

  var obj = {dt :new DateTime.now()}; 
var s = stringify(obj);

运行时会抛出异常:调用对象的toJson方法失败。



这是预期的,因为DateTime类没有 toJson 方法。
但是在这种情况下我该怎么办?



JavaScript的 JSON.stringify 函数有一个可选参数 它允许我提供我自己的任何对象的序列化方法,即使对象没有toJson方法。在Dart中是否有类似的工具或者我可以用自己的toJson方法扩展DateTime类?

解决方案

Zdeslav Vojkovic的回答是 c> dart:convert

code>有一个可选的 toEncodable 方法,该方法为不可本地序列化为JSON的对象调用。然后由用户提供一个返回适当的DateTime序列化的闭包。


I try to convert an object to JSON.

  var obj = { "dt": new DateTime.now() };
  var s = stringify(obj);

The runtime throws an exception: "Calling toJson method on object failed."

That's expected since DateTime class doesn't have toJson method. But what should I do in this case?

Javascript's JSON.stringify function has an optional argument replacer which allows me to provide my own way of serialization of any object even if the object has no toJson method. Is there any similar facility in Dart or maybe I can extend somehow DateTime class with my own toJson method?

解决方案

Zdeslav Vojkovic's answer is outdated now.

The JSON.encode() method in dart:convert has an optional toEncodable method that is invoked for objects that are not natively serializable to JSON. It's then up to the user to provide a closure that returns an appropriate serialization of the DateTime.

这篇关于如何在Dart中将包含DateTime字段的对象转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆