From af23c48a96d6c02f3915d926530e49feed6db308 Mon Sep 17 00:00:00 2001 From: Michael Bartnett Date: Sun, 17 Aug 2014 20:23:04 -0400 Subject: [PATCH] Option to force DateTimes to deserialize as Utc Conflicts: test/JsonMapperTest.cs --- src/LitJson/JsonMapper.cs | 16 +++++++++++++++- test/JsonMapperTest.cs | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/LitJson/JsonMapper.cs b/src/LitJson/JsonMapper.cs index 38d68a77..805f86ab 100644 --- a/src/LitJson/JsonMapper.cs +++ b/src/LitJson/JsonMapper.cs @@ -97,9 +97,19 @@ public IDictionary Properties { public delegate IJsonWrapper WrapperFactory (); + [Flags] + public enum JsonMapperOptions + { + None = 0x00, + DateTimesAlwaysUniversal = 0x01, + } + + public class JsonMapper { #region Fields + public static JsonMapperOptions Options; + private static int max_nesting_depth; private static IFormatProvider datetime_format; @@ -667,7 +677,11 @@ private static void RegisterBaseImporters () typeof (char), importer); importer = delegate (object input) { - return Convert.ToDateTime ((string) input, datetime_format); + DateTime result = Convert.ToDateTime((string) input, datetime_format); + if ((JsonMapper.Options & JsonMapperOptions.DateTimesAlwaysUniversal) != 0) { + result = result.ToUniversalTime(); + } + return result; }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); diff --git a/test/JsonMapperTest.cs b/test/JsonMapperTest.cs index 8a3421fe..d37ba9ef 100644 --- a/test/JsonMapperTest.cs +++ b/test/JsonMapperTest.cs @@ -196,6 +196,11 @@ public enum NullableEnum TestVal2 = 2 } + public class DateTimeTest + { + public DateTime dateTimeValue; + } + public class NullableEnumTest { public NullableEnum? TestEnum; @@ -1024,5 +1029,27 @@ public void NullableEnumExportTest() expectedJson = "{\"TestEnum\":null}"; Assert.AreEqual(expectedJson, JsonMapper.ToJson(value)); } + + [Test] + public void DateTimeShouldBeUniversalTest() + { + string json = @"{ + ""dateTimeValue"": ""2014-05-02T05:52:10.569000+00:00"" + }"; + + JsonMapper.Options = JsonMapperOptions.DateTimesAlwaysUniversal; + + DateTimeTest dateTimeTest = JsonMapper.ToObject(json); + Assert.AreEqual(DateTimeKind.Utc, dateTimeTest.dateTimeValue.Kind); + + json = @"{ + ""dateTimeValue"": ""2014-05-02T05:52:10.569000"" + }"; + + dateTimeTest = JsonMapper.ToObject(json); + Assert.AreEqual(DateTimeKind.Utc, dateTimeTest.dateTimeValue.Kind); + + JsonMapper.Options = JsonMapperOptions.None; + } } }