Forked from doggy8088/Serialize_Deserialize_Test.cs
Last active
December 18, 2015 11:09
-
-
Save pH200/5773282 to your computer and use it in GitHub Desktop.
This file contains 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
using System; | |
using System.IO; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using System.Xml; | |
using System.Xml.Serialization; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string s = "1234"; | |
string xml = SiteHelper.Serialize(s); | |
object obj = SiteHelper.Deserialize<object>(xml); | |
} | |
} | |
public static class SiteHelper | |
{ | |
public static string Serialize(object o) | |
{ | |
XmlSerializer ser = new XmlSerializer(o.GetType(), o.GetType().AssemblyQualifiedName); | |
StringBuilder sb = new StringBuilder(); | |
StringWriter writer = new StringWriter(sb); | |
ser.Serialize(writer, o); | |
return sb.ToString(); | |
} | |
public static T Deserialize<T>(string s) | |
{ | |
MemoryStream ms = new MemoryStream(Encoding.GetEncoding("UTF-16").GetBytes(s)); | |
XmlTextReader reader = new XmlTextReader(ms); | |
reader.Normalization = false; | |
var assemblyTypeString = Regex.Match(s, "xmlns=\"([^\"]+)").Groups[1].Value; | |
var assemblyType = Type.GetType(assemblyTypeString); | |
XmlSerializer ser = new XmlSerializer(assemblyType, assemblyTypeString); | |
object obj = ser.Deserialize(reader); // Exception happen!! | |
return (T)obj; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment