-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
EDIT @eiriktsarpalis: See #29932 (comment) for the API proposal.
Apologies if this is already answered somewhere else, but if it was my search abilities failed me.
I'm trying out the preview 6 of 3.0 with some existing production application code, and one of the issues that's come out of testing is that some of our existing objects we use in our API contracts use properties which are TimeSpan
values, which are then represented as strings.
Is support for TimeSpan
properties planned for 3.0 for the new System.Text.Json APIs?
If it's not going to be that gives us notice to do some refactoring ahead of September to change them to strings so we can use the new serializer, where as if it's planned but just not implemented yet then we just need to wait for a later preview to get this working.
Below is a minimal repro unit test that demonstrates the failure for TimeSpan
to be handled compared to our existing JSON .NET code.
using System;
using System.Text.Json.Serialization;
using Xunit;
using JsonConvert = Newtonsoft.Json.JsonConvert;
using JsonSerializer = System.Text.Json.Serialization.JsonSerializer;
namespace JsonSerializerTimeSpanNotSupportedException
{
public static class Repro
{
[Fact]
public static void Can_Deserialize_Object_With_SystemTextJson()
{
// Arrange
string json = "{\"child\":{\"value\":\"00:10:00\"}}";
// Act (fails in preview 6, throws: System.Text.Json.JsonException : The JSON value could not be converted to System.TimeSpan. Path: $.child.value | LineNumber: 0 | BytePositionInLine: 28.)
var actual = JsonSerializer.Parse<Parent>(json, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
// Assert
Assert.NotNull(actual);
Assert.NotNull(actual.Child);
Assert.Equal(TimeSpan.FromMinutes(10), actual.Child.Value);
}
[Fact]
public static void Can_Deserialize_Object_With_NewtonsoftJson()
{
// Arrange
string json = "{\"child\":{\"value\":\"00:10:00\"}}";
var actual = JsonConvert.DeserializeObject<Parent>(json);
// Assert
Assert.NotNull(actual);
Assert.NotNull(actual.Child);
Assert.Equal(TimeSpan.FromMinutes(10), actual.Child.Value);
}
private sealed class Parent
{
public Child Child { get; set; }
}
private sealed class Child
{
public TimeSpan Value { get; set; }
}
}
}