5

If I deserialize a timestamp contained in json to an object it loses it's millisecond precision.

var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Console.WriteLine(dict["timestamp"]);

Output:

16/06/2016 16:27:36

This happens even if I convert the object to a DateTime.

var obj = dict["timestamp"];
var timestamp = DateTime.Parse(obj.ToString());
Console.WriteLine(timestamp.ToString("yyyy/MM/dd HH:mm:ss.ffff"));

Output:

2016/06/16 16:27:36.0000
Scott
  • 928
  • 9
  • 14
  • Possible duplicate of [Force JSON.NET to include milliseconds when serializing DateTime (even if ms component is zero)](http://stackoverflow.com/questions/18193281/force-json-net-to-include-milliseconds-when-serializing-datetime-even-if-ms-com) – Geoff James Jun 25 '16 at 22:53

2 Answers2

6

The issue is merely that you are calling ToString on the DateTime in both cases and the default string representation does not include milliseconds, so they are lost.

Changing the last line of the first snippet:

var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Console.WriteLine(((DateTime)dict["timestamp"]).ToString("O"));

Gives

2016-06-16T16:27:36.8080000Z

"O" is the round-trip format that includes full precision. You may wish to use a different format.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
4

You need to change the JsonSerializerSettings and set DateParseHandling to 'None'.

var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}";
var jsonSerializerSettings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, jsonSerializerSettings);
var obj = dict["timestamp"];
Console.WriteLine(obj);

Outputs:

2016/06/16 17:27:36.8080
Scott
  • 928
  • 9
  • 14