-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
System.Text.Json can't deserialize ISO dateTime to DateOnly #102594
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis |
Possible duplicate of #85545 (maybe just related) |
I believe this was a deliberate decision for the built-in to avoid loss of information (same is true for cc @jozkee |
I think it's expected that the time portion of the datetime string will be lost when you're deserializing to a record (int PropOne, int PropB); and then you try to deserialize: {
"PropOne": 1,
"PropTwo": 2,
"PropThree": 3
} The I will try to prepare a PR for it. I will see if I manage to build it locally. If not, I guess I could rely on PR tests. |
I ran into this issue just yesterday and want to share my experience in hopes of being able to accommodate native deserialization of ISO strings to Our web apps are written in Angular and make use of the Angular Material library. Our forms use the Datepicker component with the native date adapter. All of this to say that the native date adapter does not support the ability to set the parse format, which would allow us to adjust selected dates to a format that could deserialize to
What I ultimately ended up doing is creating my own public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateOnly.FromDateTime(
DateTime.Parse(
reader.GetString()
?? DateTime.MinValue.ToString()
)
);
}
public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
} |
What about introducing a setting in the serializer options to allow or prevent loss of information then? It seems to me that both scenarios could be valid: either someone actively wants for it to "just work" and trim the data, or they might actively want to block the behavior and make their API more strict. |
Description
It looks like System.Text.Json cannot deserialize from ISO 8601 datetime string to DateOnly, which I find odd, since
DateOnly.Parse("2024-05-01T00:00:00")
works perfectly fine.Reproduction Steps
Here's the code:
Expected behavior
I'd expect no exception to be thrown and an isntance of
MyRecord
to be created.Actual behavior
An exception is thrown:
Regression?
No response
Known Workarounds
Use
DateTime
instead ofDateOnly
.Configuration
dotnet: 8.0.204
OS: Fedora 40
arch: x64
Other information
No response
The text was updated successfully, but these errors were encountered: