简体   繁体   中英

Exception when testing custom JsonConverter

We get serialized DateTimes from an API in a strange format like this: /Date(1574487012797)/ To deserialize this value with System.Text.Json , we wrote our own JsonConverter :

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var dateTimeString = reader.GetString();
        dateTimeString = dateTimeString.Replace("/Date(", "");
        dateTimeString = dateTimeString.Replace(")/", "");
        var epoch = Convert.ToInt64(dateTimeString);
        var dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(epoch);
        return dateTimeOffset.UtcDateTime;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
    }
}

I'd like to write a Unit Test for this converter. What I tried is the following:

public class DateTimeConverterTest
{
    private readonly DateTimeConverter testee;

    public DateTimeConverterTest()
    {
        this.testee = new DateTimeConverter();
    }

    [Fact]
    public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
    {
        var a = "{\r\n \"PublikationsDatum\": \"/Date(1573581177000)/\" \r\n}";
        //var serializedDateTime = "/Date(1573581177000)/";
        var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
        //utf8JsonReader.TokenType = JsonTokenType.String;
        var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});

    }

    private class TestClass
    {
        public DateTime PublikationsDatum { get; set; }
    }
}

Unfortunately, when trying to execute the Unit Test, I get an InvalidOperationException at var dateTimeString = reader.GetString();

System.InvalidOperationException: 'Cannot get the value of a token type 'None' as a string.'

How can I setup the test correctly / what am I doing wrong?

Before you can call JsonConverter<T>.Read() you must advance the Utf8JsonReader until it is positioned on the value of the "PublikationsDatum" property, eg like so:

public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
{
    var a = "{\r\n \"PublikationsDatum\": \"/Date(1573581177000)/\" \r\n}";
    var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
    while (utf8JsonReader.Read())
        if (utf8JsonReader.TokenType == JsonTokenType.String)
            break;
    var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});
}

Demo fiddle #1 here .

Alternatively, you could simplify your unit test by parsing a simple JSON string literal "/Date(1573581177000)/" . However, you will still need to advance the reader once because it is initially positioned before the beginning of the first token, with utf8JsonReader.TokenType == JsonTokenType.None :

public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
{
    var a = "\"/Date(1573581177000)/\"";
    var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
    // Reader always starts out without having read anything yet, so TokenType == JsonTokenType.None initially
    Assert.IsTrue(utf8JsonReader.TokenType == JsonTokenType.None);
    utf8JsonReader.Read();
    var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});
}

Demo fiddle #2 here .

Notes:

  • "\\/Date(number of ticks)\\/" is the format used by Microsoft's original JavaScriptSerializer for serializing a DateTime to a JSON string. See the documentation remarks for details.

    (Within a JSON string literal , \\/ is just an escaped \\ and will be silently interpreted as such by Utf8JsonReader , see fiddle #3 here . You don't need to check for \\/ within your JSON converter to handle JavaScriptSerializer generated dates and times.)

  • DataContractSerializer used a slightly different format. From the docs :

    DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

  • Newtonsoft's implementation of DateTimeUtils.TryParseDateTimeMicrosoft() may be helpful in guiding your implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM