Fluent, annotations-less, compile safe, automated, convention-based mappings for Json.NET.
Install using the Moises.Toolkit.Newtonsoft.FluentAPI NuGet package:
dotnet add package Moises.Toolkit.Newtonsoft.FluentAPI
Obs: compatible with .NetStandard, .NetCore and .NetFramework
*First, create your map:
public class TestJsonTypeConfiguration : IJsonTypeConfiguration<UserTest>
{
public void Configure(JsonTypeBuilder<UserTest> jsonTypeBuilder)
{
jsonTypeBuilder.Property(x => x.FirstName)
.HasFieldName("first_name");
jsonTypeBuilder.Property(x => x.LastName)
.HasFieldName("last_name");
jsonTypeBuilder.Property(x => x.Age)
.HasFieldName("user_age");
jsonTypeBuilder.Property(x => x.Status)
.HasFieldName("status")
.HasConverter(new StringEnumConverter());
jsonTypeBuilder.Property(x => x.City)
.IsIgnored();
}
}
*After, create your FluentContractResolver
and set the created map:
FluentContractResolver _fcr = new FluentContractResolver();
_fcr.AddConfiguration(new TestJsonTypeConfiguration());
*At the end, add your FluentContractResolver
in JsonSerializerSettings
:
- Global
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ContractResolver = _fcr
};
var model = JsonConvert.DeserializeObject<UserTest>(stringBuilder.ToString());
- Individual
var settings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ContractResolver = _fcr
};
var model = JsonConvert.DeserializeObject<UserTest>(stringBuilder.ToString(), settings);
- In AspNetCore
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.ContractResolver = new FluentContractResolver();
});
Code created from discussion in stackoverflow, being made the necessary improvements and corrections.