【问题标题】:Parse custom date format using JSON.Net使用 JSON.Net 解析自定义日期格式
【发布时间】:2011-12-28 02:38:09
【问题描述】:

我在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。

【问题讨论】:

标签: c# json serialization


【解决方案1】:

您将需要使用JSONConverter 来帮助管理翻译。详情请参阅this stackapps answer

【讨论】:

    【解决方案2】:

    这里有一些代码可以做到这一点:

    // 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_date 的类型是 int 还是 DateTime,然后根据类型切换设置对象的方式!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多