Last active
September 16, 2018 17:18
-
-
Save brainded/8698865 to your computer and use it in GitHub Desktop.
Code snippet to make a ToJson extension method for objects in C#. Relies on NewtonSoft.Json Nuget.
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
public static class ObjectExtensions | |
{ | |
/// <summary> | |
/// The string representation of null. | |
/// </summary> | |
private static readonly string Null = "null"; | |
/// <summary> | |
/// The string representation of exception. | |
/// </summary> | |
private static readonly string Exception = "Exception"; | |
/// <summary> | |
/// To json. | |
/// </summary> | |
/// <param name="value">The value.</param> | |
/// <returns>The Json of any object.</returns> | |
public static string ToJson(this object value) | |
{ | |
if (value == null) return Null; | |
try | |
{ | |
string json = JsonConvert.SerializeObject(value); | |
return json; | |
} | |
catch (Exception exception) | |
{ | |
//log exception but dont throw one | |
return Exception; | |
} | |
} | |
} |
Cool!
For me, I love to log formatted JSON. Maybe add a parameter for Formatting and default to Formatting.None?
public static string ToJson(this object value, Formatting formatting = Formatting.None)
{
if (value == null) return Null;
try
{
return JsonConvert.SerializeObject(value, formatting);
}
catch
{
//log exception but dont throw one
return Exception;
}
}
string formatted_string = new SomeObject().ToJson(Formatting.Indented)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice Job x)