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;
        }

 

posted @ 2017-05-24 16:28  小小七爷  阅读(376)  评论(0编辑  收藏  举报