.Net Core 3.0 TimeSpan (de)serialization error
I am using .Net Core 3.0 and have the following string which I need to deserialize with Newtonsoft.Json:
{
"userId": null,
"accessToken": null,
"refreshToken": null,
"sessionId": null,
"cookieExpireTimeSpan": {
"ticks": 0,
"days": 0,
"hours": 0,
"milliseconds": 0,
"minutes": 0,
"seconds": 0,
"totalDays": 0,
"totalHours": 0,
"totalMilliseconds": 0,
"totalMinutes": 0,
"totalSeconds": 0
},
"claims": null,
"success": false,
"errors": [
{
"code": "Forbidden",
"description": "Invalid username unknown!"
}
]
}
and bump into the following error:
Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.TimeSpan' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'cookieExpireTimeSpan.ticks', line 1, position 103.
The error string actually happens when reading the content of HttpResponseMessage:
var httpResponse = await _client.PostAsync("/api/auth/login", new StringContent(JsonConvert.SerializeObject(new API.Models.Request.LoginRequest()), Encoding.UTF8, "application/json"));
var stringResponse = await httpResponse.Content.ReadAsStringAsync();
The server controller method returns:
return new JsonResult(result) { StatusCode = whatever; };
https://stackoverflow.com/questions/58283761/net-core-3-0-timespan-deserialization-error
Did you mean to create the issue for Newtonsoft (not System.Text.Json)?
Closing as this issue belongs in https://github.com/JamesNK/Newtonsoft.Json.
It is an issue of System.Text.Json serializer. I've just found this error today (reported by my customer) and have to switch all of my aspnet webapi and apps to use Newtonsoft.Json serializer instead.
Using the initial example above, TimeSpan property is serialized into all of its properties (fields) instead to the standard "cookieExpireTimeSpan":"00:00:00.0000000" format.
In my cases I use nullable TimeSpan (TimeSpan?) and it is serialized as:
{ "hasValue": true, "value": { "tick":0, "days": 0, "hours": 0, "milliseconds": 0, "minutes": 0, "seconds": 0, "totalDays": 0, "totalHours": 0, "totalMilliseconds": 0, "totalMinutes": 0, "totalSeconds": 0 } }
This causes a little problem for javascript object in web browser, as well as for various deserializers consuming my api.
I would expect same serialization result as Newtonsoft.Json serializer:
{ "timeSpan": "00:00:00.0000000", "nullTimeSpan": null }
@bashocz please add your scenario to https://github.com/dotnet/corefx/issues/38641.