【发布时间】:2017-09-08 15:41:29
【问题描述】:
我们将 JSON 发送到一个由 swagger 定义的 API,其中一些属性是 DateTime,格式为 yyyy-MM-ddThh:mm:ss.000Z(毫秒必须是 3 位数字,否则在端点验证失败),有些是日期(无时间)属性。
我看到很多消息说使用这样的格式化程序:
var jsonSettings = new JsonSerializerSettings();
jsonSettings.DateFormatString = "yyyy-MM-ddThh:mm:ss.000Z"; //try .fffZ too
var jsonObject= Newtonsoft.Json.JsonConvert.DeserializeObject<OurSwaggerObject>(json , setting);
但这不会将 DateTimes 转换为正确的格式,C# 如何处理仅 Date 类型?它似乎总是序列化为 DateTime.MinValue()
这是一个例子:
有人将 json 作为字符串发送给我,但是格式不正确的日期和日期时间要发送到端点。我希望 swagger 类和 json 反序列化会格式化它们,但事实并非如此。
这是swagger生成的类
public class OurSwaggerObject
{
[Newtonsoft.Json.JsonProperty("dateTimeField", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
[System.ComponentModel.DataAnnotations.RegularExpression(@"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$")]
public DateTime dateTimeField { get; set; }
[Newtonsoft.Json.JsonProperty("dateField", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
[System.ComponentModel.DataAnnotations.RegularExpression(@"^\d{4}-\d\d-\d\d$")]
public DateTime dateField { get; set; }
}
所以我尝试强制 json 正确,但我做错了或缺少某些东西
string json = @"{ 'dateTimeField': '1995-04-07T00:00:00',
'dateField': '1995-04-07T00:00:00'
}";
/* The json we need to satisfy the swagger endpoint is:
{ 'dateTimeField': '1995-04-07T00:00:00.000Z',
'dateField': '1995-04-07'
}
*/
OurSwaggerObject deserialisedIntoObject = Newtonsoft.Json.JsonConvert.DeserializeObject<OurSwaggerObject>(json);
string serialisedToString = Newtonsoft.Json.JsonConvert.SerializeObject(deserialisedIntoObject);
//serialisedToString= "{\"dateTimeField\":\"1995-04-07T00:00:00\",\"dateField\":\"1995-04-07T00:00:00\"}"
var jsonSettings = new JsonSerializerSettings();
jsonSettings.DateFormatString = "yyyy-MM-ddThh:mm:ss.fffZ"; //this won't help much for the 'date' only field!
deserialisedIntoObject = Newtonsoft.Json.JsonConvert.DeserializeObject<OurSwaggerObject>(json,jsonSettings);
serialisedToString = Newtonsoft.Json.JsonConvert.SerializeObject(deserialisedIntoObject, jsonSettings);
//serialisedToString="{\"dateTimeField\":\"1995-04-07T00:00:00\",\"dateField\":\"1995-04-07T00:00:00\"}"
【问题讨论】:
-
请提供说明问题的mcve
-
Json.NET 从 4.5 版开始使用事实上的标准(当前是 10.x)。它确实正确地序列化日期。格式字符串仅用于 older 版本。发布实际显示问题的代码
-
另一方面,如果另一个端点需要任意数量的毫秒,那么问题就出在他们身上。 ISO8601 不需要毫秒
-
仅限日期 - Json 没有日期或时间。这就是为什么提到 defacto 标准的原因。在某些时候,人们只是决定开始使用 ISO8601。日期可以由 DateTime 值表示。您可以将其序列化为 Json,或者作为具有零小时、分钟的完整 ISO8601 字符串,或者作为仅日期字符串。都是有效的。
-
Swagger OpenAPi 确实定义了日期和日期时间 swagger.io/specification 我将发布一些代码示例
标签: c# json date datetime json.net