'How to apply custom deserialization to DateTimeOffset field by System.Text.Json
How should I configure my deserializations to behave differently according to the data in json. When the time field contains an offset (like in the example payload1), I would like the deserialized object to have the offset as in the payload. And when the time field does not contain an offset (like in the example payload2) , I would like it to be interpreted as in UTC. In short I would like the below test to be successful. Would you please advise?
public class UnitTest1
{
public class TestObj
{
[JsonPropertyName("time")]
public DateTimeOffset? Time { get; set; }
}
[Fact]
public void Test1()
{
string payload1 = "{ \"time\": \"2022-03-17T07:31:00-04:00\" }";
TestObj deserializedPayload1 = System.Text.Json.JsonSerializer.Deserialize<TestObj>(payload1);
Assert.Equal("-04:00:00", deserializedPayload1.Time.Value.Offset.ToString());
string payload2 = "{ \"time\": \"2022-03-17T07:31:00\" }";
TestObj deserializedPayload2 = System.Text.Json.JsonSerializer.Deserialize<TestObj>(payload2);
Assert.Equal("00:00:00", deserializedPayload2.Time.Value.Offset.ToString());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
