Created
April 12, 2018 14:56
-
-
Save longtth/dbbadc96bf4a2c30f512e0f5f4257cdc to your computer and use it in GitHub Desktop.
Json Serialization , copy from https://codereview.stackexchange.com/questions/100850/json-serialization-helper-class
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
/// <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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment