// convert JSON <-> CLASS
public static string ToJSON( this object obj )
{
if ( !IsSerializable(obj) )
{
throw new Exception("Target object must be serializable.");
}
string json = string.Empty;
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
using ( MemoryStream ms = new MemoryStream() )
{
ser.WriteObject(ms, obj);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
public static bool IsSerializable( this object obj ) { MemoryStream ms = null; BinaryFormatter bf = null; try { ms = new MemoryStream(); bf = new BinaryFormatter(); bf.Serialize(ms, obj); return true; } catch ( System.Runtime.Serialization.SerializationException ) { return false; } catch ( Exception exc ) { throw exc; } finally { ms.Close(); ms.Dispose(); } }
public static T FromJSON<T>( this string json ) { using ( MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json)) ) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); return (T)ser.ReadObject(ms); } }