今天需要使用Json數據,所以用到了Json的序列化與反序列化。首先先來說怎麼序列化的:
首先添加System.Runtime.Serialization的引用
public static string ObjectToJson(object obj) { DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, obj); return Encoding.Default.GetString(ms.ToArray()); } }
public static T JsonToObject<T>(string json) where T : class { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(json))) { return (T)ser.ReadObject(ms); } }
程序比較簡單我就不多說了,剛開始實體類是這樣的:
[Serializable] class User { public int Age { get; set; } public string Name { get; set; } public User(string name, int age) { Age = age; Name = name; } }
然後調用:
static void Main(string[] args) { var user1 = new User("zhangsan", 18); var users = new List<User> { user1, new User("lisi", 23 ) }; var strUser1 = ObjectToJson(user1); var setUsers = ObjectToJson(users); }
加入斷點,查看json數據,
居然莫名其妙出現了亂入的k__BackingField
從網上找了好多資料也沒搞明白是為啥會出現這個問題。想了解的可以參考下這個。不過找到了解決方案,這裡記錄下:
只需要將實體類改成如下形式:
[DataContract] class User { [DataMember] public int Age { get; set; } [DataMember] public string Name { get; set; } public User(string name, int age) { Age = age; Name = name; } }
再監視下就不會出現k__BackingField。Json數據轉換成實體的調用也很簡單:
static void Main(string[] args) { var user1 = new User("zhangsan", 18); var users = new List<User> { user1, new User("lisi", 23 ) }; var strUser1 = ObjectToJson(user1); var strUsers = ObjectToJson(users); var user11 = JsonToObject<User>(strUser1); var users1 = JsonToObject<List<User>>(strUsers); }