JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.73k stars 3.25k forks source link

JToken.ToObject(JsonSerializer jsonSerializer) ignores jsonSerializer parameter when converting DateTime to string #2840

Open PavelHruschka opened 1 year ago

PavelHruschka commented 1 year ago

I have JSON { "field": "myField", "operator": "eq", "value": "2023-03-21T12:34:56Z" } this is parsed to JToken and the "value" property is parsed as DateTime

then I have C# object FilterItem public class FilterItem { public string Field { get; set; } public string Operator { get; set; } public string Value { get; set; } // Value is string - just wanna get the same value as is in the JSON }

when I call myJToken.ToObject() or myJToken.ToObject(new JsonSerializer{ DateFormatString = "yyyy-MM-ddTHH:mm:ssK"})

then I get: myFilterItem.Value: "3/21/2023 12:34:56"

I looked at the JsonReader.cs there is if (v is IFormattable formattable) { s = formattable.ToString(null, Culture); } else { s = v is Uri uri ? uri.OriginalString : v.ToString()!; }

So every primitive type is treated as ToString with InvariantCulture format when serialized to the destination property of type string. In my opinion, it should respect jsonSerializer parameter (and its settings) of JToken.ToObject method. Or default format, eg.: JsonSerializerSettings.DefaultDateFormatString, but do not use ToString(InvariantCulture) without the ability to change it...

I solved it using DateParseHandling.None when parsing string to JToken, but it seems to me as bug that ToObject ignores jsonSerializer settings and always do ToString...

Thank you.