dotnet / dotnet/aspnetcore

JsonConverter not called on deserialization when set as property attribute

Open
#54,181 2 comments 2 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

The `Read` method in the custom `HoursMinutesOnlyJsonConverter` is never called during deserialization of a .net core API project. The `Request` class is being used inside a few `Controllers` with a `[FromBody]` tag.

```
public class Request
{
[JsonConverter(typeof(HoursMinutesOnlyJsonConverter))]
public TimeOnly? Time { get; set; }
}
```

```
public class Response
{
[JsonConverter(typeof(HoursMinutesOnlyJsonConverter))]
public TimeOnly? Time { get; set; }
}
```

```
public class HoursMinutesOnlyJsonConverter : JsonConverter
{
public override TimeOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// THIS IS NEVER BEING CALLED
return null;
}

public override void Write(Utf8JsonWriter writer, TimeOnly? value, JsonSerializerOptions options)
{
// THIS WORKS AS EXPECTED
if (value == null)
{
writer.WriteNullValue();

}
else
{
writer.WriteStringValue(((TimeOnly)value).ToString("hh:mm"));
}
}
}
```

### Expected Behavior

The custom converter should be called during deserialization.

### Steps To Reproduce

_No response_

### Exceptions (if any)

_No response_

### .NET Version

8.0.101

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.