Home > OS >  System.Text.Json.Serialization replacement for Netwtonsoft's JsonObjectAttribute NamingStrategy
System.Text.Json.Serialization replacement for Netwtonsoft's JsonObjectAttribute NamingStrategy

Time:08-03

For those of you who have done more .NET 6 than me, have you found a replacement for Netwonsoft's JsonObjectAttribute's NamingStrategy setting?

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class PortConfig
{
    public string Http { get; set; }
    public string Https { get; set; }
}

I want something that I can stamp on the CLASS to declare its property's naming strategy, rather than having to put a JsonPropertyName("CamelCaseName") attribute on each property.

CodePudding user response:

You can pass options to the serializer

var options = new System.Text.Json.JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

Or in your startup you can configure the default

.AddJsonOptions(opts =>
{
    opts.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
})

Another option is to use JsonSourceGenerationOptions if you don't want to configure it globally or use serializer options

How to use source generation in System.Text.Json

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
public class PortConfig
{
    public string Http { get; set; }
    public string Https { get; set; }
}

If you need to build a custom naming class the documentation is here Custom Json Property Naming

  • Related