简体   繁体   English

在 JsonConvert.SerializeObject 中更改日期时间格式

[英]Change DateTime format in JsonConvert.SerializeObject

I have a class called "Data" and it has "Name", "Date" and "Value".我有一个名为“数据”的类,它有“名称”、“日期”和“值”。 The "Date" Attribute is a DateTime value. “日期”属性是一个日期时间值。

Now I have a List<Data> called "DataList" and I use the JsonConvert function on it like:现在我有一个名为“DataList”的List<Data> ,我在它上面使用了 JsonConvert 函数,例如:

Newtonsoft.Json.JsonConvert.SerializeObject(DataList)

But now the Date is displayed like this YYYY-MM-DDTHH-mm-SS.但现在日期显示为 YYYY-MM-DDTHH-mm-SS。 Can I somehow Change this format before the JsonConvert is done?我可以在 JsonConvert 完成之前以某种方式更改此格式吗?

If I understand correctly, what you want to do could be achieved by specifying the format as a parameter to the SerializeObject method.如果我理解正确,可以通过将格式指定为 SerializeObject 方法的参数来实现您想要做的事情。

Something like this:像这样的东西:

var dt = DateTime.Now;
JsonSerializerSettings formatSettings = new JsonSerializerSettings
{
    DateFormatString = "dd/MM/yyyy"
};
var json = JsonConvert.SerializeObject(dt, formatSettings);

See this page for examples on how to do it: https://www.newtonsoft.com/json/help/html/DatesInJSON.htm有关如何操作的示例,请参阅此页面: https : //www.newtonsoft.com/json/help/html/DatesInJSON.htm

Don't do it.不要这样做。

This is not answering the question, because it is so bad, it should only be looked into as a last resort.这不是在回答问题,因为它太糟糕了,只能将其作为最后的手段。

JSON, while being humanly readable, is an object serialisation standard to be used across systems. JSON 虽然是人类可读的,但它是一种跨系统使用的对象序列化标准。 If you need to tweak the format, something is wrong.如果您需要调整格式,那就有问题了。

The serialized date/time format is in ISO8601 form.序列化日期/时间格式采用ISO8601格式。 It has been chosen so that every system that complies to that standard can interpreter the string correctly.选择它是为了让每个符合该标准的系统都可以正确解释字符串。

Strings like:字符串如:

2018-09-20T09:23:46+00:00 2018-09-20T09:23:46+00:00

are perfectly readable, causing no ambiguity, and will deserialize correctly by any system which uses the default settings.完全可读,不会造成歧义,并且可以被任何使用默认设置的系统正确反序列化。

Deviation from these kind of standards can give you serious issues while trying to maintain the system, cross device or cross culture.在尝试维护系统、跨设备或跨文化时,偏离这些标准可能会给您带来严重的问题。

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

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