Newtonsoft.Json使用MySqlDateTime

时间:2018-05-28 01:27:17

标签: c# json json.net

我在DataTable中得到一种MySqlDateTime,它是从MySql中选择的,就像从t_storage'中选择deliverytime,然后填入DataTable。现在我想通过Newtonsoft.Json将此DataTable转换为json,但它无法获取日期时间,它总是转换为null。下面是一些代码:

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

我尝试过使用IsoDateTimeConverter来合成日期,但它不起作用。

我确定dt.Rows [0] [" deliverrtime"]是一种MySqlDateTime,并且该值不为null。我可以使用'((MySql.Data.Types.MySqlDateTime)dt.Rows [0] [" deliverrtime"])。GetDateTime()'将其转换为DataTime类型。在t_storage中,列传递时间是日期时间的类型。

任何想法?

1 个答案:

答案 0 :(得分:0)

Json.NET使用的默认格式是ISO 8601标准:“2012-03-19T07:22Z”。如果您获得的格式不同,那么您可以在序列化时定义DateTimeFormat IsoDateTimeConverter。你可以阅读它here

因此将序列化逻辑定义为

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