如何将DateTime对象转换为json [英] How to convert DateTime object to json

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

问题描述

如何将 DateTime 对象转换为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.

推荐答案

除了使用包装器,您还可以创建自己的自定义编码器传递 toEncodable 参数。

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;
}

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

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