Skip to content

Instantly share code, notes, and snippets.

@jchandra74
Created April 14, 2015 00:07
Show Gist options
  • Save jchandra74/b9c9b46d053f5662a503 to your computer and use it in GitHub Desktop.
Save jchandra74/b9c9b46d053f5662a503 to your computer and use it in GitHub Desktop.
Serialization Helper
namespace __NAMESPACE__
{
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
using JsonSerializer = ServiceStack.Text.JsonSerializer;
using XmlSerializer = System.Xml.Serialization.XmlSerializer;
public static class ObjectSerialiserExtension
{
public static Stream SerializeToStream(this Object obj)
{
if (obj == null)
return null;
var bf = new BinaryFormatter();
var ms = new MemoryStream();
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
public static XmlDocument SerializeToXml<T>(this T model)
{
var xmls = new XmlSerializer(typeof(T));
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
xmls.Serialize(writer, model);
}
var xml = new XmlDocument();
xml.LoadXml(sb.ToString());
return xml;
}
public static Object DeserializeToObject(this byte[] arrBytes)
{
var ms = new MemoryStream();
var bf = new BinaryFormatter();
ms.Write(arrBytes, 0, arrBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
var obj = bf.Deserialize(ms);
return obj;
}
public static T DeserializeTo<T>(this byte[] arrBytes)
{
return (T)DeserializeToObject(arrBytes);
}
public static string SerializeToJson<T>(this T source)
{
return JsonSerializer.SerializeToString(source, typeof (T));
}
public static T DeserializeFromJson<T>(this string jsonString)
{
return JsonSerializer.DeserializeFromString<T>(jsonString);
}
public static string SerializeToJson2<T>(this T source)
{
return JsonConvert.SerializeObject(source);
}
public static T DeserializeFromJson2<T>(this string jsonString)
{
return JsonConvert.DeserializeObject<T>(jsonString);
}
public static T DeserializeTo<T>(this XmlDocument source)
{
T result;
using (var reader = XmlReader.Create(new StringReader(source.OuterXml)))
{
result = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment