C#Newtonsoft.Json无法解析日期

时间:2018-05-27 00:04:05

标签: c# json json.net

我在我的项目中使用Newtonsoft.Json来从服务器进行json解析。

public class MyObj
{
    public DateTimeOffset TimeStamp { get; set; }
    //other fields....
}

然后:

MyObj test = JsonConvert.DeserializeObject<MyObj>(jObject.ToString());

测试:

"TimeStamp": "2018-05-26T04:59:40:888Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T04:59:40:88Z"  //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T14:59:40:888Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T14:59:40:88Z"  //Could not convert string to DateTimeOffset

"TimeStamp": "2018-05-26T03:29:46.777Z" //works
"TimeStamp": "2018-05-26T13:29:46.77Z"  //works
"TimeStamp": "2018-05-26T03:29:46.777Z" //works
"TimeStamp": "2018-05-26T13:29:46.77Z"  //works

错误:

  

Newtonsoft.Json.JsonReaderException:无法将字符串转换为DateTimeOffset:2018-05-27T04:59:40:887Z。

我不确定为什么会发生这种情况,因为日期来自服务器。

编辑:

{
  "clientTimestamp": "2018-05-27T06:08:40:688Z",
  "modifiedType": "",
  "type": "TEXT",
  "messageSize": 5,
  "roomId": "689355a0-604b-11e8-ae6a-9d170520ec46",
  "messageContent": "hello"
}

更新我终于找到了问题。这不是我正在解析的服务器响应。我解析的是我自己的对象。说明:

public class TempClass
{
    public DateTime TimeStamp { get; set; }
}

不起作用

JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss:fffZ"));
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());

作品

JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now);
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());

2 个答案:

答案 0 :(得分:3)

您的时间戳不正确

而不是2018-05-27T06:08:40:688Z应该是2018-05-27T06:08:40.688Z (毫秒由点.分隔)

试试这个

public class RootObject
{
    public DateTime clientTimestamp { get; set; }
    public string modifiedType { get; set; }
    public string type { get; set; }
    public long messageSize { get; set; }
    public Guid roomId { get; set; }
    public string messageContent { get; set; }
}

然后:

MyObj test = JsonConvert.DeserializeObject<RootObject>(jObject.ToString());

实际上

2018-05-27T06:08:40:688Z
   无法将字符串转换为DateTime:2018-05-27T06:08:40.688Z

2018-05-27T06:08:40.688Z
   行

答案 1 :(得分:1)

似乎发生了这种情况,因为来自服务器的数据没有以正确的日期/时间json格式发送,而您正在尝试反序列化它们。