1.必须应用System.serviceModel.Web;
2.应用System.Runtime.Serialization.Json;System.Runtime.Serialization;
3.coding
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="Entity"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public static string SerializeObject<Entity>(Entity entity)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(entity.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, entity);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
ms.Close();
return sb.ToString();
}
}
public static string SerializeObject<Entity>(IList<Entity> entityList)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(entityList.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, entityList);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
ms.Close();
return sb.ToString();
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="Entity"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static Entity DeSerilizeObject<Entity>(string jsonString)
{
DataContractJsonSerializer deserialize = new DataContractJsonSerializer(typeof(Entity));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
Entity entity = (Entity)deserialize.ReadObject(ms);
ms.Close();
return entity;
}
}