Created
May 28, 2021 12:43
-
-
Save mishrsud/c7c193d65374b454fdab3a688b70c122 to your computer and use it in GitHub Desktop.
Customised Serialization with System.Text.Json
This file contains hidden or 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 System.Text.Json; | |
using System.Text.Json.Serialization; | |
namespace Infrastructure | |
{ | |
public static class JsonSerializationExtensions | |
{ | |
public static JsonSerializerOptions DefaultSerializerOptions = new JsonSerializerOptions | |
{ | |
WriteIndented = false, | |
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, | |
PropertyNameCaseInsensitive = true, | |
IgnoreNullValues = true, | |
Converters = { new JsonStringEnumConverter(allowIntegerValues: false) } | |
}; | |
public static string ToJson<T>(this T objectToSerialize) | |
{ | |
return JsonSerializer.Serialize(objectToSerialize, DefaultSerializerOptions); | |
} | |
public static T FromJson<T>(this string json) | |
{ | |
return json == null ? default : JsonSerializer.Deserialize<T>(json, DefaultSerializerOptions)!; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment