C# json、xml序列化
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; }
内容为小七在工作中遇到或在其他地方看到所做的总结,方便以后查看,仅供学习使用;
转载请注明出处;