Skip to content

ClausStolz/JsonStringCaseConverter

Repository files navigation

JsonStringCaseConverter

GitHub license NuGet Badge

Info

JsonStringCaseConverter is the string case formatting extensions for System.Text.Json.

This library helps to convert strings to the following formats:

  • Camel case;
  • Pascal case;
  • Snake case;
  • Cebab case (comming soon).

Installation

Either checkout this Github repository or install JsonStringCaseConverter via NuGet Package Manager.

If you want to use NuGet just search for JsonStringCaseConverter or run the following command in the NuGet Package Manager console:

PM> Install-Package JsonStringCaseConverter

Usage

In a part of System.Text.Json

To work with the object, use the inherited class JsonStringCaseNamingPolicy. The JsonStringCaseNamingPolicy class receives one of the formats you need in the constructor stored in the StringCases enam. The following formats are currently available:

public enum StringCases
{
    CamelCase,
    SnakeCase,
    PascalCase
}

To configure for JsonSerializer directly:

var options = new JsonSerializerOptions()
{
    PropertyNamingPolicy = new JsonStringCaseNamingPolicy(StringCases.CamelCase)
};

var json = JsonSerializer.Serialize(obj, options);

To configure for .NET Core project:

services.AddControllers()
    .AddJsonOptions(options => 
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = new JsonStringCaseNamingPolicy(StringCases.PascalCase)
    });

To configure for .NET 6.0 Minimal API:

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = new JsonStringCaseNamingPolicy(StringCases.SnakeCase));
});

In a native work with strings

The library has direct extension methods that can be used with non-json strings if you need them.

var camelText = someText.ToCamelCase();

var snakeText = someText.ToSnakeCase();

var pascalText = someText.ToPascalCase();

There is also an extension of the separating string into words with case register.

var words = someText.SplitForWords();
// words = ["some", "Text", "WITH", "SaVing", "case", "REGISTER"]

About

String case formatting extensions for System.Text.Json

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages