SteveDunn / Vogen

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Apache License 2.0
894 stars 46 forks source link

Add ReadAsPropertyName and WriteAsPropertyName for System.Text.Json #386

Closed newbe36524 closed 1 year ago

newbe36524 commented 1 year ago

Describe the feature

It need to impl this methods when the struct is used for a key type of a dictionary. e.g. Dictionary<UserId, string>

there is an example

[ValueObject<ulong>(conversions: Conversions.None)]
[JsonConverter(typeof(UserIdJsonConverter))]
public readonly partial struct UserId
{
    private static Validation Validate(ulong input)
    {
        return Validation.Ok;
    }
}

internal class UserIdJsonConverter : JsonConverter<UserId>
{
    public override UserId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var id = reader.GetUInt64();
        return UserId.From(id!);
    }

    public override void Write(Utf8JsonWriter writer, UserId value, JsonSerializerOptions options)
    {
        writer.WriteNumberValue(value.Value);
    }

    public override UserId ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert,
        JsonSerializerOptions options)
    {
        var id = reader.GetString();
        return UserId.From(ulong.Parse(id!));
    }

    public override void WriteAsPropertyName(Utf8JsonWriter writer, UserId value, JsonSerializerOptions options)
    {
        writer.WritePropertyName(value.ToString());
    }
}
SteveDunn commented 1 year ago

Thanks for the feedback - a great idea. I'm working on this now so should be release within a day or two.

Thanks again!

SteveDunn commented 1 year ago

Implemented in https://github.com/SteveDunn/Vogen/releases/tag/3.0.14