Skip to content

Commit

Permalink
Merge pull request #150 from manuc66/feature/DateTime_issue_with_1.8.…
Browse files Browse the repository at this point in the history
…0_#120_

Should fix DateTime issue with 1.8.0
  • Loading branch information
manuc66 authored Oct 18, 2022
2 parents 87abcbf + 5456006 commit 6ea8df4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
16 changes: 11 additions & 5 deletions JsonSubTypes.Tests/DatesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,26 @@ public class SubTypeClass : MainClass
{
public string Discriminator => "SubTypeClass";

public DateTimeOffset? Date { get; set; }
public DateTimeOffset? DateTimeOffset { get; set; }
public DateTime? DateTime { get; set; }
}

[Test]
public void DeserializingSubTypeWithDateParsesCorrectly()
{
var json = "{ \"Discriminator\": \"SubTypeClass\", \"Date\": \"2020-06-28T00:00:00.00000+00:00\" }";
var json = "{ \"Discriminator\": \"SubTypeClass\", \"DateTime\": \"2020-06-28T00:00:00.00000+00:00\", \"DateTimeOffset\": \"2020-06-28T00:00:00.00000+00:00\" }";

var obj = JsonConvert.DeserializeObject<MainClass>(json);
var obj = JsonConvert.DeserializeObject<MainClass>(json, new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.DateTimeOffset
});

Assert.That(obj, Is.Not.Null);
Assert.That(obj, Is.InstanceOf<SubTypeClass>());
Assert.That(((SubTypeClass)obj).Date.HasValue, Is.True);
Assert.That(((SubTypeClass)obj).Date.Value.Offset, Is.EqualTo(TimeSpan.Zero));
Assert.That(((SubTypeClass)obj).DateTimeOffset.HasValue, Is.True);
Assert.That(((SubTypeClass)obj).DateTimeOffset.Value.Offset, Is.EqualTo(TimeSpan.Zero));
Assert.That(((SubTypeClass)obj).DateTime.HasValue, Is.True);
Assert.That(((SubTypeClass)obj).DateTime.Value, Is.EqualTo(new DateTime(2020,6,28,0,0,0,0)));
}
}
}
5 changes: 0 additions & 5 deletions JsonSubTypes/JsonSubtypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,7 @@ private static Type GetElementType(Type arrayOrGenericContainer)

private object ReadObject(JsonReader reader, Type objectType, JsonSerializer serializer)
{
// I would prefer to create a new reader, but can't work out how to
// This seems a reasonable alternative - https://github.com/JamesNK/Newtonsoft.Json/issues/1605#issuecomment-602673364
var savedDateParseSettings = reader.DateParseHandling;
reader.DateParseHandling = DateParseHandling.None;
var jObject = JObject.Load(reader);
reader.DateParseHandling = savedDateParseSettings;

var targetType = GetType(jObject, objectType, serializer) ?? objectType;

Expand Down

0 comments on commit 6ea8df4

Please sign in to comment.