aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

JsonConverter not called on deserialization when set as property attribute

Open wadeamaral opened this issue 1 year ago • 2 comments

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<TimeOnly?>
 {
     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

wadeamaral avatar Feb 23 '24 00:02 wadeamaral

Having the same problem. Are there any updates?

maets avatar Jun 17 '25 14:06 maets

Solved my own issue by adding the following override to my custom converter: public override bool HandleNull => true;

I guess it's optimized by circumventing the converter if encountering null or something like that

maets avatar Jun 17 '25 22:06 maets