Using System.IO;
Using System.Text;
Using System.Xml.Serialization;
Using System.Xml;
Using System.Runtime.Serialization.Json;
Namespace Common.core
{
public class Serializationhelper
{
private static string Xmlserialize (object o)
{
XmlSerializer ser = new XmlSerializer (O.gettype ());
System.IO.MemoryStream mem = new MemoryStream ();
XmlTextWriter writer = new XmlTextWriter (mem, Encoding.UTF8);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces ();
Ns. Add ("", "");
Ser. Serialize (writer, o, NS);
Writer. Close ();
Return Encoding.UTF8.GetString (Mem. ToArray ());
}
private static T xmldeserialize<t> (string s)
{
XmlDocument Xdoc = new XmlDocument ();
Try
{
Xdoc. LOADXML (s);
XmlNodeReader reader = new XmlNodeReader (Xdoc. DocumentElement);
XmlSerializer ser = new XmlSerializer (typeof (T));
Object obj = ser. Deserialize (reader);
Return (T) obj;
}
Catch
{
return default (T);
}
}
private static string Jsonserialize (object o)
{
using (var ms = new MemoryStream ())
{
New DataContractJsonSerializer (O.gettype ()). WriteObject (MS, O);
Return Encoding.UTF8.GetString (Ms. ToArray ());
}
}
private static T jsondeserialize<t> (string s)
{
using (var ms = new MemoryStream (Encoding.UTF8.GetBytes (s)))
{
Return (t) new DataContractJsonSerializer (typeof (T)). ReadObject (MS);
}
}
//<summary>
//Serializes the object according to format (Xml/json) into a string result
//</summary>
//<param name= "O" > Target object and Lt;/param>
//<param name= "format" > Output format </param>
///<returns></returns>
public static string Serialize (object o, format format)
{
if (format = = Format.xml)
{
return serialization Helper.xmlserialize (o);
}
Else
{
return serializationhelper.jsonserialize (o);
}
}
<summary>
Deserializes a string into an object of the specified type according to format (Xml/json)
</summary>
<typeparam name= "T" > Specify Type </typeparam>
<param name= "S" > Target string </param>
<param name= "format" > Input format </param>
<returns></returns>
public static T deserialize<t> (string s, format format)
{
if (format = = Format.xml)
{
return serializationhelper.xmldeserialize<t> (s);
}
Else
{
return serializationhelper.jsondeserialize<t> (s);
}
}
}
}
C # JSON to XML