简体   繁体   中英

Custom Json Converter For Nullable Value Type Does Not Get Called

I have two custom converters for Uuid value type. One for nullable and other for not nullable:

public class NullableUuidJsonConverter : JsonConverter<Uuid?>
{
    public override bool HandleNull => true;

    public override Uuid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (Uuid.TryParse(reader.GetString(), out var parsedUuid))
        {
            return parsedUuid;
        }
        
        return null;
    }

    public override void Write(Utf8JsonWriter writer, Uuid? value, JsonSerializerOptions options)
    {
        if (value == null)
        {
            writer.WriteStringValue((string)null);
        }
        else
        {
            writer.WriteStringValue(value.Value.ToString());
        }
    }
}

public class UuidJsonConverter : JsonConverter<Uuid>
{
    public override Uuid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return new Uuid(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, Uuid value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}

And they registered like this:

.AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Converters.Insert(0, new UuidJsonConverter());
                    options.JsonSerializerOptions.Converters.Insert(1, new NullableUuidJsonConverter());
                });

When I try to call API method which request model contains nullable Uuids:

[PublicAPI]
public class Request : IRequest<Response>
{
    [FromQuery(Name = "ids")] public Uuid[] CheckupIds { get; set; }
    [FromQuery(Name = "unitId")][CanBeNull] public Uuid? UnitId { get; set; }
    [FromQuery(Name = "ratingPeriodId")][CanBeNull] public Uuid? RatingPeriodId { get; set; }
}

UnitId and RatingPeriodId are filled with null. However if I make them simple not nullable Uuid they will be filled with actual passed values.

Thanks for you replies. I managed to fix this issue by using publicly available nuget Dodo.Primitives.Uuid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM