码迷,mamicode.com
首页 > Windows程序 > 详细

c# json TO xml

时间:2015-03-14 21:20:10      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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>
/// 将对象根据格式(XML/JSON)序列化成字符串结果
/// </summary>
/// <param name="o">目标对象</param>
/// <param name="format">输出格式</param>
/// <returns></returns>
public static string Serialize(object o, Format format)
{
if (format == Format.Xml)
{
return SerializationHelper.XmlSerialize(o);
}
else
{
return SerializationHelper.JsonSerialize(o);
}
}

/// <summary>
/// 将字符串根据格式(XML/JSON)反序列化成指定类型的对象
/// </summary>
/// <typeparam name="T">指定类型</typeparam>
/// <param name="s">目标字符串</param>
/// <param name="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

标签:

原文地址:http://www.cnblogs.com/FredTang/p/4338105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!