1、使用 JavaScriptSerializer类实现序列化
namespace: System.Web.Script.Serialization
eg:
1 // 序列化 2 private string ObjectToJson(Person obj) 3 { 4 JavaScriptSerializer jsonSerialize = new JavaScriptSerializer(); 5 return jsonSerialize.Serialize(obj); 6 } 7 // 反序列化 8 private Person JsonToObject(string jsonStr) 9 { 10 JavaScriptSerializer jsonSerialize = new JavaScriptSerializer(); 11 return jsonSerialize.Deserialize<Person>(jsonStr); 12 }
注:可用 [ScriptIgnore] 标记不序列化的属性
2、使用 DataContractJsonSerializer类实现序列化
namespace:System.Runtime.Serialization.Json
eg:
1 // 序列化 2 using (MemoryStream stream =new MemoryStream()) 3 { 4 DataContractJsonSerializer jsonSerialize =new DataContractJsonSerializer(Person); 5 jsonSerialize.WriteObject(stream, obj); 6 jsonStr = Encoding.UTF8.GetString(stream.ToArray()); 7 } 8 // 反序列化 9 using (MemoryStream stream =new MemoryStream(Encoding.UTF8.GetBytes(jsonStr))) 10 { 11 DataContractJsonSerializer jsonSerialize =new DataContractJsonSerializer(Person); 12 obj = (Person)jsonSerialize.ReadObject(stream); 13 }
注:可用 [IgnoreDataMember] 标记不序列化的属性
时间: 2024-10-12 22:00:34