使用 Json.Net 以 dd/MM/yyyy 格式反序列化日期 [英] Deserializing dates with dd/MM/yyyy format using Json.Net
问题描述
我正在尝试将对象从 JSON 数据反序列化为 C# 类(我使用的是 Newtonsoft Json.NET).数据包含作为字符串值的日期,例如 09/12/2013
,其中格式为 dd/MM/yyyy
.
I'm trying to deserialize an object from JSON data to a C# class (I'm using Newtonsoft Json.NET). The data contains dates as string values like 09/12/2013
where the format is dd/MM/yyyy
.
如果我调用 JsonConvert.DeserializeObject
,日期以 MM/dd/yyyy
格式加载到 C# 类的 DateTime
属性,这导致日期值为 2013 年 9 月 12 日
(而不是 2013 年 12 月 9 日
).
If I call JsonConvert.DeserializeObject<MyObject>(data)
,
dates are loaded to the DateTime
property of the C# class with the MM/dd/yyyy
format, this causes the date value to be 12 September 2013
(instead of 9 December 2013
).
是否可以配置 JsonConvert
以获取正确格式的日期?
Is it possible to configure JsonConvert
to get the date in the correct format?
推荐答案
您可以使用 IsoDateTimeConverter
并指定 DateTimeFormat
以获得您想要的结果,例如:
You can use an IsoDateTimeConverter
and specify the DateTimeFormat
to get the result you want, e.g.:
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonString,
new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });
演示:
class Program
{
static void Main(string[] args)
{
string json = @"{ ""Date"" : ""09/12/2013"" }";
MyObject obj = JsonConvert.DeserializeObject<MyObject>(json,
new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });
DateTime date = obj.Date;
Console.WriteLine("day = " + date.Day);
Console.WriteLine("month = " + date.Month);
Console.WriteLine("year = " + date.Year);
}
}
class MyObject
{
public DateTime Date { get; set; }
}
输出:
day = 9
month = 12
year = 2013
这篇关于使用 Json.Net 以 dd/MM/yyyy 格式反序列化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!