首页 > Windows开发 > 详细

C# json、xml序列化

时间:2017-05-24 16:47:48      阅读:271      评论:0      收藏:0      [点我收藏+]

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

 

C# json、xml序列化

原文:http://www.cnblogs.com/xiaoxiaoqiye/p/6899618.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!