1.JSON序列化。
首先,引用程序集 System.Runtime.Serialization, 我们要使用System.Runtime.Serialization.Json,默认点不出来,这应该是一个扩展方法。所以还需要引入以下两个程序集:
System.ServiceModel
System.ServiceModel.Web
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO; namespace FirsteLite.OMS.Business.Helper
{
public static class JsonHelper
{
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serilializer = new DataContractJsonSerializer(typeof(T));
using (Stream stream = new MemoryStream())
{
serilializer.WriteObject(stream, obj);
stream.Flush();
stream.Position = ;
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
} public static T Deserialize<T>(string source)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(source)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
}
示例如下:
var p1 = new Person
{
Name = "NanFei",
Age = ,
Gender = ,
BirthDay = DateTime.Now
}; var p2 = new Person
{
Name = "FanJinfei",
Age = ,
Gender = ,
BirthDay = DateTime.Now
}; var personList = new List<Person>();
personList.Add(p1);
personList.Add(p2); var json = JsonHelper.Serialize<List<Person>>(personList);
var list = JsonHelper.Deserialize<List<Person>>(json);
2.DataContract序列化,这种兼容的可序列化类型多一些。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Runtime.Serialization; namespace FirsteLite.OMS.Business.Helper
{
public static class DataContractHelper
{
public static ILog log = LogManager.GetLogger(typeof(DataContractHelper)); public static string Serialize<T>(T obj)
{
try
{
using (var ms = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
catch (Exception ex)
{
log.Error("序列化类型" + typeof(T).Name + "时发生错误。", ex);
return null;
} } public static T Deserialize<T>(string value)
{
try
{
var serializer = new DataContractSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(value)))
{
return (T)serializer.ReadObject(ms);
}
}
catch (Exception ex)
{
log.Error("反序列化类型" + typeof(T).Name + "时发生错误。", ex);
return default(T);
} }
}
}