andrewlock / StronglyTypedId

A Rosyln-powered generator for strongly-typed IDs
MIT License
1.52k stars 79 forks source link

Use System.Text.Json instead of Newtonsoft #9

Closed darbio closed 4 years ago

darbio commented 4 years ago

ASP.Net Core 3.1 uses System.Text.Json to serialize objects. It would be good to support this new method of serialization.

I currently use the following (obviously it would need adapting to support the relevant use cases in this package).

public class MemberIdConverter : JsonConverter<MemberId>
{
    public override MemberId Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) =>
            new MemberId(Guid.Parse(reader.GetString()));

    public override void Write(
        Utf8JsonWriter writer,
        MemberId value,
        JsonSerializerOptions options) =>
            writer.WriteStringValue(value.Value);
}

This issue depends upon #5

andrewlock commented 4 years ago

Agreed, seems like a good addition!

vebbo2 commented 4 years ago

Hi @andrewlock, I am up for implementing this, but I need your opinion. I think it's good idea to enable to pick which serializer you want to use, and have support for both System.Text.Json and Newtonsoft.Json.

This requires changes in StronglyTypedIdAttribute parameters. My proposition is to add new enum parameter jsonProvider (which would default to StronglyTypedIdJsonProvider.NewtonsoftJson):

// no provider needed
[StronglyTypedId(generateJsonConverter: false, backingType: StronglyTypedIdBackingType.Int)]

// old behavior, generates converter for Newtonsoft.Json
[StronglyTypedId(backingType: StronglyTypedIdBackingType.Int)]

// one specific
[StronglyTypedId(jsonConverter: StronglyTypedIdJsonProvider.NewtonsoftJson, backingType: StronglyTypedIdBackingType.Int)]
[StronglyTypedId(jsonConverter: StronglyTypedIdJsonProvider.SystemTextJson, backingType: StronglyTypedIdBackingType.Int)]

// both of them, because why not?
[StronglyTypedId(jsonConverter: StronglyTypedIdJsonProvider.NewtonsoftJson | StronglyTypedIdJsonProvider.SystemTextJson, backingType: StronglyTypedIdBackingType.Int)]

Are you okay with that approach?

andrewlock commented 4 years ago

Sounds good to me, thanks! 🙂

andrewlock commented 4 years ago

Thanks to @vebbo2 for implementing this in https://github.com/andrewlock/StronglyTypedId/pull/11, I'll push out a release to NuGet shortly