JsonUtils類,注意引用
Newtonsoft.Json.dll
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace Practice.SerDeser
{
public class JsonUtils
{
// 從一個對象資訊生成Json串
public static string ObjectToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
// 從一個Json串生成對象資訊
public static object JsonToObject(string jsonString, object obj)
{
return JsonConvert.DeserializeObject(jsonString, obj.GetType());
}
// List轉換成json字元串
public static string ListToJson(List<object> list)
{
return JsonConvert.SerializeObject(list);
}
// json字元串轉換成List
public static T JsonToList<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
}
}
XmlUtils工具類:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
namespace Practice.SerDeser
{
public class XmlUtils
{
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">類型</param>
/// <param name="obj">對象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化對象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
#region 反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">類型</param>
/// <param name="xml">XML字元串</param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
}
}