Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify global settings for Json.Net for DateTime serialization/deserialization

Tags:

json.net

Is it possible to set JSON.Net such that if you want to serialize a DateTime, it is serialized to UTC format. When deserializing from a string, it is deserialized to 'LocalTime'. For example:

  • Serialization
    • 01/01/2012 16:00:00 (Kind = UTC) Stored as 2012-01-01T16:00:00Z
    • 01/01/2012 16:00:00 (Kind = Local, with GMT +1) -> Stored as 2012-01-01T15:00:00Z
  • Deserialization (assuming machine with Local Time = GMT+1)
    • 2012-01-01T16:00:00Z -> Deserialized to 01/01/2012 17:00 +1GMT (Kind = Local)
    • 2012-01-01T15:00:00Z -> Deserialized to 01/01/2012 16:00 +1GMT (Kind = Local)

However, I would like this to happen 'automatically', and not having to specify it with setttings each time - Like a global setting. Is this possible?

like image 891
Karl Cassar Avatar asked Jul 08 '26 22:07

Karl Cassar


1 Answers

In ASP.NET WebAPI, it is possible. Try this:

// Converters will be userd during serialization (override DateTimeZoneHandling)
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AdjustToUniversal });
// DateTimeZoneHandling will be effective during deserialization
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
like image 84
Masayuki Muto Avatar answered Jul 13 '26 21:07

Masayuki Muto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!