Last active
March 4, 2021 09:46
-
-
Save maximgorbatyuk/9725efc4956b27642da697a83f451ec9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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