JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.76k stars 3.25k forks source link

DefaultContractResolver and fluent configuration #2950

Open adambajguz opened 5 months ago

adambajguz commented 5 months ago

Hello, In 2015 there was an idea of having fluent converters/configuration built into the library. These days it'll be even more cool to have this to e.g. not spoil domain layer with JSON attributes.

The official answer is that it can be build using the exisitng API. I tried, and it's hard. A lot of API is internal and the DefaultContractResolver itself heavily relies on attributes meaning it is not easy to customize some aspects of it e.g. constructor selection.

Below is a draft of the configuration builder that will be passed to the contract resolver:

    configuration.ConfigureDefaults(static o => 
    {
       o.DeserializeUsingParameterlessConstructor();
       o.NoDeserializeUsingParameterlessConstructor();

       o.DeserialiuzUsingParametrizedConstructor();

       o.IncludeProperties(Visibility.Public)
        .ExcludeFields();

       o.EnableJsonIgnoreAttributeSupport();

       o.EnableSystemTextJson_JsonPropertyNameAttributeSupport();
    })
    .Configure<ExampleClass>(static o => 
    {       
       o.DisableJsonIgnoreAttribute();
       o.DisableJsonConstructorAttribute();

       o.SelectConstructor(...);

       o.For(x => x.Prop1, static o => 
       {
            o.Name("prop_01);
            o.Required();
       });

       o.For(x => x.Prop2, static o => 
       {
            o.Ignore();
       });

       o.For(x => x.Prop3).Ignore();

       o.For(x => x.Prop4).ShouldSerialize(...);
       o.For(x => x.Prop4).ShouldDeserialize(...);

       o.OnSerializing(...);
    });

@JamesNK What is the current opinion on having sth like this in Newtonsoft.Json?

I think this will modernize the library a bit and make it more unique and feature-packed compared to System.Text.Json