当前位置: 代码迷 >> JavaScript >> C#序列化字符串,对象,xml,json,会合数组,字典
  详细解决方案

C#序列化字符串,对象,xml,json,会合数组,字典

热度:1622   发布时间:2013-12-26 15:24:01.0
C#序列化字符串,对象,xml,json,集合数组,字典

1.对象和xml的序列化和反序列化:

先随便建一个实体类

 public class Person
    {
        public Person()
        {
        }

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; set; }

        public int Age { get; set; }

        public DateTime LastLoginTime { get; set; }

        public List<Course> Courses = new List<Course>();
    }
 public class Course
    {
        public Course()
        {
        }

        public Course(string name, string description)
        {
            Name = name;
            Description = description;
        }

        public string Name
        {
            get;
            set;
        }

        public string Description
        {
            get;
            set;
        }
    }

??对象和xml序列化和反序列化方法

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="filePath"></param>
        public static void Serialiaze(String filePath)
        {
            Person c = new Person("James Chen",35);
            c.Courses.Add(new Course("高等数学", "思维工具"));
            c.Courses.Add(new Course("大学英语", "交流工具"));
            c.Courses.Add(new Course("离散数学", "计算机理论"));
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            xs.Serialize(stream, c);
            stream.Close();
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="filePath"></param>
        public static void Deserialize(String filePath)
        {
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            Person p = (Person)xs.Deserialize(stream);
            stream.Close();
        }

?调用方法

string path = Server.MapPath("upload/test.xml");
Serializer.Serialiaze(path);
Serializer.Deserialize(path);

?

2.字符串和对象的序列化和反序列化

/// <summary>
        /// 序列化 对象到字符串
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string Serialize<T>(T obj)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception("序列化失败,原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 反序列化 字符串到对象
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <param name="str">要转换为对象的字符串</param>
        /// <returns>反序列化出来的对象</returns>
        public static T Desrialize<T>(T obj, string str)
        {
            try
            {
                obj = default(T);
                IFormatter formatter = new BinaryFormatter();
                byte[] buffer = Convert.FromBase64String(str);
                MemoryStream stream = new MemoryStream(buffer);
                obj = (T)formatter.Deserialize(stream);
                stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("反序列化失败,原因:" + ex.Message);
            }
            return obj;
        }

?调用方法

//序列化
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            dt.Rows.Add(new object[] { 1, "first" });
            dt.Rows.Add(new object[] { 2, "second" });
            string result = SerializeUtilities.Serialize(dt);
            Response.Write(result);

            //反序列化
            string mystr = result;
            DataTable _resDT = new DataTable();

            _resDT = (DataTable)SerializeUtilities.Desrialize(_resDT, mystr);

            Response.Write("<br>反序列化结果<br>" + _resDT.Rows[0][0].ToString() + ":" + _resDT.Rows[0][1].ToString() + "<br>");
            Response.Write(_resDT.Rows[1][0].ToString() + ":" + _resDT.Rows[1][1].ToString() + "<br>");

?

3.JSON序列化和反序列化的处理

 /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }


        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializerM<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            //替换Json的Date字符串
            string p = @"\\/Date\((\d+)\+\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(p);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserializeM<T>(string jsonString)
        {
            //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(p);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }

        /// <summary>
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            return result;
        }

        /// <summary>
        /// 将时间字符串转为Json时间
        /// </summary>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }

?调用代码

Person p = new Person();
            p.Name = "张三";
            p.LastLoginTime = DateTime.Now;

            p.Age = 28;
            string jsonString = JsonSerializeHelper.JsonSerializer<Person>(p);
            Response.Write(jsonString);
            Person pe = JsonSerializeHelper.JsonDeserialize<Person>(jsonString);

            ///JSON序列化和反序列化日期时间的处理
            Person p2 = new Person();
            p2.Name = "张三";
            p2.Age = 28;
            p2.LastLoginTime = DateTime.Now;

            string jsonString2 = JsonSerializeHelper.JsonSerializerM<Person>(p);
            Person pe2 = JsonSerializeHelper.JsonDeserializeM<Person>(jsonString);
 ///JSON序列化和反序列化集合、字典、数组的处理
            List<Person> list = new List<Person>()
            {
                new Person(){ Name="张三", Age=28,LastLoginTime = DateTime.Now},
                new Person(){ Name="李四", Age=25,LastLoginTime = DateTime.Now}
            };

            string jsonString3 = JsonSerializeHelper.JsonSerializer<List<Person>>(list);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("Name", "张三");
            dic.Add("Age", "28");

            string jsonString4 = JsonSerializeHelper.JsonSerializer<Dictionary<string, string>>(dic);

?

  相关解决方案