Meteor.js使用Json.NET将DDP日期转换为C#DateTime

时间:2014-08-01 10:17:33

标签: c# meteor json.net ddp

问:如何让Json.NET成功将此json日期结构转换为C#DateTime?

您好,我正在尝试使用DDP协议将现有Meteor.js应用程序上的方法调用的返回值反序列化为已知/严格的返回结构。

我正在使用动态来实现最基本的东西,但是,继续使用严格的结构以从C#方面获得类型安全和智能感知。

但是,使用javascripts Date()的ddp序列化结构无法将Javascripts Date()成功反序列化为C#s DateTime:

"when": {
        "$date": 1406886657338
 }

问:如何让Json.NET成功将此json日期结构转换为C#DateTime?

如果是"协议"中间件是可能的,具有DateTime到DDPs Date()也很棒。

我的结构:

namespace xxxx.API.Structures
{
    public struct loginParams
    {
        public string email;
        public string apiClient;
    }

    public struct loginReturn
    {
        public string result;
        public string session;
        public string email;
        public string user;
        public DateTime when;
        public string client;
    }
}

我想要转换为loginReturn的返回值:

xxxx.DDP.Client.DDPClient.ConnectGS.AnonymousMethod__1 (err=(null), res={{
  "result": "sucess",
  "session": "v3gozkHgceoqGqsfd",
  "email": "xxxx@gmail.com",
  "user": "hueun3s8rKQWsoQDT",
  "server": "Lnf3vAFaeoCiMWriY",
  "when": {
    "$date": 1406886657338
  },
  "client": "OfficialxxxxPlugin"
}}) in /Volumes/2TB/Files/Documents/Dropbox/Development/C#/xxxx/xxxx/xxxxAPI/xxxx.DDP.Client/DDPClient.cs:43

2 个答案:

答案 0 :(得分:0)

JSON响应中的值是Unix时间戳。它给出了自1970年1月1日00:00:00 UTC以来的毫秒数。

所以你可以这样做:

String JSONDate = "1406886657338";
DateTime when = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(JSONDate));

答案 1 :(得分:0)

这不是最好的解决方案,并没有真正为我想讨论的主题添加任何内容,但是,对于这个特定问题,这是一个有效的修复。

private static Regex _dollarDateRegex = new Regex ("\"\\$date\\\":\\s?(\\d+)");
if (message.Contains ("$date")) {
                var matches = _dollarDateRegex.Matches (message);
                foreach (Match match in matches) {
                    string date = match.Groups [1].Value;
                    int startOfDate = message.IndexOf ("$date\":" + date, StringComparison.CurrentCulture);
                    int startOfObject = startOfDate;
                    int endOfObject = startOfDate;
                    // skip to first { behind
                    while (message [startOfObject--] != '{') {
                    }
                    // skip to last } in front
                    while (message [endOfObject++] != '}') {
                    }                       
                    var diff = endOfObject - startOfObject;
                    StringBuilder s = new StringBuilder (message);
                    s.Remove (startOfObject, diff);
                    s.Insert (startOfObject, ": new Date(" + date + ")");
                    message = s.ToString ();
                }
            }

这会产生:

{
   ...
   when: new Date(2191283823),
   ...
}