简体   繁体   English

Newtonsoft.Json使用MySqlDateTime序列化数据表

[英]Newtonsoft.Json serialize datatable with MySqlDateTime

I get a type of MySqlDateTime in a DataTable, which is select from MySql, just like 'select delivertime from t_storage', and then fill into a DataTable. 我在DataTable中得到了一种MySqlDateTime,它是从MySql中选择的,就像“从t_storage中选择交付时间”,然后填充到DataTable中。 Now I want convert this DataTable into json by Newtonsoft.Json, but it can not get the datetime, it's always convert null. 现在我想通过Newtonsoft.Json将此DataTable转换为json,但无法获取日期时间,它始终转换为null。 Some code belows: 下面的一些代码:

DataTable dt = new DataTable();
string sql = "select ig, gid, delivertime from t_storage";
MariadbHelper db = new MariadbHelper();// a dbhelper 
db.excute(sql).Fill(dt);// pull the sql result into dt
string ret = JsonConvert.SerializeObject(dt, Formatting.Indented);// the delivertime is null: [ {"id":1, "gid":1, "delivertime":null}]

I have tried use IsoDateTimeConverter to formate the date, but it does not work. 我曾尝试使用IsoDateTimeConverter设置日期,但无法正常工作。

I am sure dt.Rows[0]["delivertime"] is a type of MySqlDateTime, and the value is not null. 我确定dt.Rows [0] [“ delivertime”]是MySqlDateTime的一种,其值不为null。 I can use '((MySql.Data.Types.MySqlDateTime)dt.Rows[0]["delivertime"]).GetDateTime()' to convert it into DataTime type. 我可以使用'(((MySql.Data.Types.MySqlDateTime)dt.Rows [0] [“ delivertime”])。GetDateTime()'将其转换为DataTime类型。 In t_storage, the column delivertime is type of datetime. 在t_storage中,列deliverytime是日期时间的类型。

Any idears? 有想法吗?

The default format used by Json.NET is the ISO 8601 standard: "2012-03-19T07:22Z". Json.NET使用的默认格式是ISO 8601标准:“ 2012-03-19T07:22Z”。 If you are getting a string in a different format then you can defined the DateTimeFormat of IsoDateTimeConverter while serializing. 如果获取的字符串格式不同,则可以在序列化时定义IsoDateTimeConverterDateTimeFormat You can read about it here . 你可以在这里阅读。

So define the Serialization logic as 因此,定义序列化逻辑为

string ret = JsonConvert.SerializeObject(dt, new IsoDateTimeConverter() { DateTimeFormat = "yyyy/M/d H:m:ss" });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM