json序列化:
public static string SerializeJson<T>(T json) { // 1. 需要添加引用 Newtonsoft.Json.dll,默认为 Json.NET return Newtonsoft.Json.JsonConvert.SerializeObject(json); // 2. 需要添加引用 System.Web.Extensions,然后添加命名空间 System.Web.Script.Serialization; //return new JavaScriptSerializer().Serialize(json); } public static T DeserializeJson<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); //JavaScriptSerializer Serializer = new JavaScriptSerializer(); //return Serializer.Deserialize<T>(json); }
XML序列化:
public static string ToXml<T>(T item) { XmlSerializer xmlSerializer = new XmlSerializer(item.GetType()); StringBuilder stringBuilder = new StringBuilder(); string result; using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder)) { xmlSerializer.Serialize(xmlWriter, item); result = stringBuilder.ToString(); } return result; } public static T FromXml<T>(string str) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); T result; using (XmlReader xmlReader = new XmlTextReader(new StringReader(str))) { result = (T)((object)xmlSerializer.Deserialize(xmlReader)); } return result; }
时间: 2024-11-05 13:36:46