项目引用
System.Runtime.Serialization.dll
添加命名空间
using System.Runtime.Serialization.Json;
1.序列化对象,得到Json字符串
public static string WriteFromObject<T>(T obj) where T : class { DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { dcjs.WriteObject(ms, obj);
//ms.Position = 0;
//byte[] bt = new byte[ms.Length];
//ms.Read(bt, 0, bt.Length);
//return Encoding.Default.GetString(bt);
return Encoding.Default.GetString(ms.ToArray()); } }
2.反序列化对象 ,从Json字符串中得到对象
public static T ReadToObject<T>(string json) where T : class { DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Default.GetBytes(json))) { return dcjs.ReadObject(ms) as T; } }
3.对象示例
/// 实现可序列化数据协定 [System.Runtime.Serialization.DataContract] /// 识别方法返回类型 [System.Runtime.Serialization.KnownType("KnownType")] public class ClassSample { /// 可被序列化成员 [System.Runtime.Serialization.DataMember] public int DataMember { get; set; } /// 枚举成员也要序列化 [System.Runtime.Serialization.EnumMember] public Example EnumMember; /// 非数据协定成员忽略序列化 [System.Runtime.Serialization.IgnoreDataMember] public int IgnoreDataMember { get; set; } /// 序列化时可缺少的字段 [System.Runtime.Serialization.OptionalField] public int OptionalField; //反序列化后立即调用 [System.Runtime.Serialization.OnDeserialized] //反序列化时调用 [System.Runtime.Serialization.OnDeserializing] //在序列化该对象图后是否调用该方法 [System.Runtime.Serialization.OnSerialized] //在对象序列化前调用此方法 [System.Runtime.Serialization.OnSerializing] public KnownType KnownType() { return null; } } [System.Runtime.Serialization.DataContract] public enum Example { } [System.Runtime.Serialization.DataContract] public class KnownType { }