Reputation: 12953
I am using Newtonsoft.Json in my project for json parsing from server.
public class MyObj
{
public DateTimeOffset TimeStamp { get; set; }
//other fields....
}
Then:
MyObj test = JsonConvert.DeserializeObject<MyObj>(jObject.ToString());
Test:
"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
Error:
Newtonsoft.Json.JsonReaderException: Could not convert string to DateTimeOffset: 2018-05-27T04:59:40:887Z.
I am not sure why this happens, because the date is from server.
Edit:
{
"clientTimestamp": "2018-05-27T06:08:40:688Z",
"modifiedType": "",
"type": "TEXT",
"messageSize": 5,
"roomId": "689355a0-604b-11e8-ae6a-9d170520ec46",
"messageContent": "hello"
}
Update I finally found the issue. It was not the server response that I was parsing. It was my own object that I parsed. The description:
public class TempClass
{
public DateTime TimeStamp { get; set; }
}
Does not work
JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss:fffZ"));
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());
Works
JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now);
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());
Upvotes: 0
Views: 7558
Reputation: 133
It seems that this is happening because data from your server is not sent in the correct json format for the Date/Time, and you are trying to deserialize them.
Upvotes: 0
Reputation: 17647
Your timestamp is incorrect
Instead of 2018-05-27T06:08:40:688Z
should be 2018-05-27T06:08:40.688Z
(the millisecond is separated by a dot .
)
Try this
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; }
}
Then:
MyObj test = JsonConvert.DeserializeObject<RootObject>(jObject.ToString());
In fact
2018-05-27T06:08:40:688Z
Could not convert string to DateTime: 2018-05-27T06:08:40.688Z
2018-05-27T06:08:40.688Z
OK
Upvotes: 3