不调用可空值类型的自定义 Json 转换器

Custom Json Converter For Nullable Value Type Does Not Get Called

我有两个 Uuid 值类型的自定义转换器。一个用于可为空,另一个用于不可为空:

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());
    }
}

他们是这样注册的:

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

当我尝试调用 API 请求模型包含可为空 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和RatingPeriodId填空。但是,如果我使它们变得简单且不可空 Uuid,它们将填充实际传递的值。

感谢您的回复。我设法通过使用公开可用的 nuget Dodo.Primitives.Uuid

解决了这个问题