使用JSON.Net解析自定义日期格式

时间:2011-12-27 16:40:46

标签: c# json serialization

我在following format收到了一个JSON日期:

"launch_date": 1250553600

如何修改以下内容以包含允许我将该数字转换为DateTime对象的自定义DateTime解析器?

JsonConvert.DeserializeObject<NTask>(json);

public sealed class NTask
{
    public DateTime launch_date { get; set; }
}

或者我可以使用long,然后在另一个字段中解析它,但我宁愿避免这样做,并让JsonConvert通过某个转换器自动将其解析为DateTime。

2 个答案:

答案 0 :(得分:3)

您将要使用JSONConverter来帮助管理翻译。有关详细信息,请参阅this stackapps answer

答案 1 :(得分:1)

以下是一些代码:

// This is an example of a UNIX timestamp for the date/time 11-04-2005 09:25.    
double timestamp = 1113211532;

// First make a System.DateTime equivalent to the UNIX Epoch.    
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

// Add the number of seconds in UNIX timestamp to be converted.    
dateTime = dateTime.AddSeconds(timestamp);

代码:

    JsonConvert.DeserializeObject<NTask>(json);  

    public sealed class NTask
    {
        public DateTime launch_date { get; set; }

        public void SetLaunchDate(int timestamp)
        {
            // First make a System.DateTime equivalent to the UNIX Epoch.    
            var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            // Add the number of seconds in UNIX timestamp to be converted.    
            launch_date = dateTime.AddSeconds(timestamp);
        }
    }

然后,当您反序列化JSON时,请检查launch_dateint类型还是DateTime,并根据类型切换设置对象的方式!