Skip to content

Instantly share code, notes, and snippets.

@brainded
Last active September 16, 2018 17:18
Show Gist options
  • Save brainded/8698865 to your computer and use it in GitHub Desktop.
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.
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;
}
}
}
@colinblaise
Copy link

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