I wrote this class to one-line all my JSON serialization, and I'm curious of any input on it.
It's only responsible for serializing/deserializing any type to/from JSON.
The comments and code are pretty self explanatory, but if you want any extra explanation of it please feel free to comment.
Not a lot here, so comment on what you can.
/// <summary>
/// Provides methods for Serialization and Deserialization of JSON/JavaScript Object Notation documents.
/// </summary>
public class JsonSerialization
{
/// <summary>
/// Serializes an object to a JSON/JavaScript Object Notation string.
/// </summary>
/// <typeparam name="T">The type of the object to serialize.</typeparam>
/// <param name="value">The object to serialize.</param>
/// <param name="serializedJson">Filled with a string that is the JsonSerialized object.</param>
/// <param name="throwErrors">If true, will throw errors. Otherwise, returns false on failures.</param>
/// <returns>A boolean value indicating success.</returns>
public static bool Serialize<T>(T value, ref string serializedJson, bool throwErrors = false)
{
if (value == null)
{
return false;
}
#if DEBUG
#warning When in DEBUG Mode JavaScript Serialization Errors will be thrown regardless of throwErrors parameter.
throwErrors = true;
#endif
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
serializedJson = jss.Serialize(value);
return true;
}
catch
{
if (throwErrors)
throw;
return false;
}
}
/// <summary>
/// Deserializes a JSON/JavaScript Object Notation string to an object.
/// </summary>
/// <typeparam name="T">The type of the object to serialize.</typeparam>
/// <param name="value">The JSON string representing the serialized object.</param>
/// <param name="deserializedObject">Filled with the object that is the JsonSerialized string.</param>
/// <param name="throwErrors">If true, will throw errors. Otherwise, returns false on failures.</param>
/// <returns>A boolean value indicating success.</returns>
public static bool Deserialize<T>(string value, ref T deserializedObject, bool throwErrors = false)
{
if (value == null)
{
return false;
}
#if DEBUG
#warning When in DEBUG Mode JavaScript Deserialization Errors will be thrown regardless of throwErrors parameter.
throwErrors = true;
#endif
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
deserializedObject = jss.Deserialize<T>(value);
return true;
}
catch
{
if (throwErrors)
throw;
return false;
}
}
}