Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Json.NET DeserializeObject change the timezone to local time?

I'm using json.net to deserialize a DateTimeOffset, but it is ignoring the specified timezone and converting the datetime to the local offset. For example, given

var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}"; 

When deserialised using:

var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind }; var obj = JsonConvert.DeserializeObject(content, jsonSerializerSettings); 

The obj will contain a property containing a DateTimeOffset but the value will be 2012-07-19T15:30:00+10:30 i.e. converted to the local timezone instead of preserving the original timezone.

Is there a way to get the value to be parsed as expected so that the resulting DateTimeOffset property will match the supplied value?

like image 980
Dave Capper Avatar asked Jul 19 '12 04:07

Dave Capper


People also ask

Does JsonConvert DeserializeObject throw?

DeserializeObject can throw several unexpected exceptions (JsonReaderException is the one that is usually expected). These are: ArgumentException.

What is DeserializeObject JSON C#?

Deserialization. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is DateTimeOffset C#?

The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).


1 Answers

It seems to be ignoring DateParseHandling.DateTimeOffset and is using DateParseHandling.DateTime. I would log an issue here: https://github.com/JamesNK/Newtonsoft.Json

like image 64
Peter Ritchie Avatar answered Oct 10 '22 15:10

Peter Ritchie