using Newtonsoft.Json; using System; using System.IO; using System.Text; using System.Xml.Serialization; namespace Sarand.Net.Standard.Base.Utils { //======================================================================= public static class SerializableUtil { //------------------------------------------------------------------- /// /// Perform a deep Copy of the object. /// /// The type of object being copied. /// The object instance to copy. /// The copied object. public static T DeepCopy(T source) { // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) return default(T); // initialize inner objects individually // for example in default constructor some list property initialized with some values, // but in 'source' these items are cleaned - // without ObjectCreationHandling.Replace default constructor values will be added to result var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), deserializeSettings); } //------------------------------------------------------------------- // Serialize using JSON. public static String ToJson(T source) { // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) return ""; // Serialise to JSON String. return JsonConvert.SerializeObject(source); } //------------------------------------------------------------------- // Serialize using XML. public static String ToXml(T source) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (Stream stream = new MemoryStream()) { serializer.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); } } public static T FromXml(String data) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(data ?? ""))) { return (T)serializer.Deserialize(stream); } } //------------------------------------------------------------------- } //======================================================================= }