Skip to content

Instantly share code, notes, and snippets.

@maximgorbatyuk
Last active March 4, 2021 09:46
Show Gist options
  • Save maximgorbatyuk/9725efc4956b27642da697a83f451ec9 to your computer and use it in GitHub Desktop.
Save maximgorbatyuk/9725efc4956b27642da697a83f451ec9 to your computer and use it in GitHub Desktop.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Utils.Helpers;
namespace YourNamespace
{
public static class JsonSerializationExtensions
{
private static readonly SnakeCaseNamingStrategy _snakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();
private static readonly JsonSerializerSettings _snakeCaseSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = _snakeCaseNamingStrategy
}
};
public static string ToSnakeCase<T>(this T instance)
{
if (instance == null)
{
throw new ArgumentNullException(paramName: nameof(instance));
}
return JsonConvert.SerializeObject(instance, _snakeCaseSettings);
}
public static string ToSnakeCase(this string @string)
{
if (@string == null)
{
throw new ArgumentNullException(paramName: nameof(@string));
}
return _snakeCaseNamingStrategy.GetPropertyName(@string, false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment