JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET

Home Page:https://www.newtonsoft.com/json

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DefaultContractResolver and fluent configuration

adambajguz opened this issue · comments

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