C# 使用Json.NET将Meteor.js DDP日期转换为C DateTime
问:如何使Json.NET成功地将这个Json日期结构转换为C日期时间 您好,我正在尝试使用DDP协议将现有Meteor.js应用程序上方法调用的返回值反序列化为已知/严格的返回结构 我正在使用dynamics来实现最基本的东西,但是,继续使用严格的结构,以从Cs端的类型安全和IntelliSense中获益 但是,无法使用Javascripts日期的ddp序列化结构成功地将Javascripts日期反序列化为Cs DateTime:C# 使用Json.NET将Meteor.js DDP日期转换为C DateTime,c#,meteor,json.net,ddp,C#,Meteor,Json.net,Ddp,问:如何使Json.NET成功地将这个Json日期结构转换为C日期时间 您好,我正在尝试使用DDP协议将现有Meteor.js应用程序上方法调用的返回值反序列化为已知/严格的返回结构 我正在使用dynamics来实现最基本的东西,但是,继续使用严格的结构,以从Cs端的类型安全和IntelliSense中获益 但是,无法使用Javascripts日期的ddp序列化结构成功地将Javascripts日期反序列化为Cs DateTime: "when": { "$date": 1406
"when": {
"$date": 1406886657338
}
问:如何使Json.NET成功地将这个Json日期结构转换为C日期时间
如果一个协议中间件是可能的,那么将DateTime设置为DDPs日期也会有些困难
我的结构:
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
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));
这并不是最好的解决方案,也没有给我想讨论的主题增加任何内容,但是,对于这个特定的问题,这里有一个可行的解决方案
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),
...
}
对不起,我一定没有正确地解释我自己。我想让Json.NET为我转换值,使用某种类型的转换重载或协议更改,让它转换所有这些$date,因为$date意味着它是一个特殊字段,在序列化和反序列化整个对象/字符串时,需要在不同的事务中使用它。您提供的代码是正确的,是的,但是,它不是解决方案的核心。我想为键以$date开头的字段添加一个例外。