XML/JSON序列化和反序列化

XML/JSON序列化和反序列化

 

   

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization;

//namespace I77SvrProxy
//{
    public static class SUtils
    {
        public static List<Dictionary<string, string>> GetList(string[][] Params)
        {
            List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
            foreach (string[] p in Params)
            {
                Dictionary<string, string> row = new Dictionary<string, string>();
                for (int i = 0; i < p.Length / 2; i += 2)
                    row.Add(p[i], p[i + 1]);
                result.Add(row);
            }
            return result;
        }
    }

    /// <summary>
    /// XML序列化工具
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class ObjectXMLSerializer<T>
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="Object">对象</param>
        /// <returns>返回XML文档字符</returns>
        public static string Serialize(T Object)
        {
            if (typeof(T).Equals(typeof(string[][])))
            {
                Object obj = Object;
                string[][] list = (string[][])obj;

                XmlDocument xmlDoc = new XmlDocument();
                XmlElement root = xmlDoc.CreateElement("List");
                foreach (string[] item in list)
                {
                    XmlElement row = xmlDoc.CreateElement("Row");

                    for (int i = 0; i < item.Length; i += 2)
                    {
                        XmlElement col = xmlDoc.CreateElement(item[i]);
                        col.InnerText = item[i + 1];
                        row.AppendChild(col);
                    }

                    root.AppendChild(row);
                }
                return root.InnerXml;
            }
            else if (typeof(T).Equals(typeof(List<Dictionary<string, string>>)))
            {
                Object obj = Object;
List<Dictionary<string, string>> list = (List<Dictionary<string, string>>)obj;
                XmlDocument xmlDoc = new XmlDocument();
                XmlElement root = xmlDoc.CreateElement("List");
                foreach (Dictionary<string, string> item in list)
                {
                    XmlElement row = xmlDoc.CreateElement("Row");
                    foreach (string Key in item.Keys)
                    {
                        XmlElement col = xmlDoc.CreateElement(Key);
                        col.InnerText = item[Key];
                        row.AppendChild(col);
                    }
                    root.AppendChild(row);
                }
                xmlDoc.AppendChild(root);
                return xmlDoc.OuterXml;
            }
            else
            {
                string XMLText;
                XmlSerializer ser = new XmlSerializer(typeof(T));
                MemoryStream stream = new MemoryStream();
                ser.Serialize(stream, Object);
                XMLText = Encoding.UTF8.GetString(stream.GetBuffer());
                stream.Close();
                return XMLText.Trim().Replace("\0", "");
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="XMLDocument">XML文档字符</param>
        /// <returns>返回对象</returns>
        public static T Deserialize(string XMLDocument)
        {
            if (typeof(T).Equals(typeof(List<Dictionary<string, string>>)))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(XMLDocument);

                List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
                foreach (XmlElement row in xmlDoc.FirstChild.ChildNodes)
                {
                    Dictionary<string, string> rowItem = new Dictionary<string, string>();
                    foreach (XmlElement col in row.ChildNodes)
                        rowItem.Add(col.Name, col.InnerText);
                    result.Add(rowItem);
                }
                Object obj = result;
                return (T)obj;
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(XMLDocument.Trim());
                ms.Write(buffer, 0, buffer.Length);
                ms.Seek(0, SeekOrigin.Begin);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                return (T)xs.Deserialize(ms);
            }
        }

        /// <summary>
        /// 序列化列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string SerializeList(List<T> list)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("List");
            foreach (T obj in list)
            {
                XmlElement objDoc = doc.CreateElement("ObjectDocument");
                objDoc.InnerText = Serialize(obj);
                root.AppendChild(objDoc);
            }
            doc.AppendChild(root);
            return doc.OuterXml;
        }

        /// <summary>
        /// 反序列化列表
        /// </summary>
        /// <param name="XMLDocument"></param>
        /// <returns></returns>
        public static List<T> DeserializeList(string XMLDocument)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XMLDocument);
            List<T> result = new List<T>();
            foreach (XmlElement element in doc.SelectNodes("List/ObjectDocument"))
            {
                result.Add(Deserialize(element.InnerText));
            }
            return result;
        }

        public static void SerializeBinary(T Obj, string FilePath)
        {
            if (File.Exists(FilePath)) File.Delete(FilePath);
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, Obj);
            stream.Close();
        }

        public static T DeserializeBinary(string FilePath)
        {
            if (!File.Exists(FilePath))
                return default(T);
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            T Obj = (T)formatter.Deserialize(stream);
            stream.Close();
            return Obj;
        }

        public static byte[] SerializeBinary(T Obj)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, Obj);
            stream.Seek(0, SeekOrigin.Begin);
            byte[] byteArray = new byte[stream.Length];
            stream.Read(byteArray, 0, byteArray.Length);
            stream.Close();
            return byteArray;
        }

        public static T DeserializeBinary(byte[] bytes)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = BytesToStream(bytes);
            T Obj = (T)formatter.Deserialize(stream);
            stream.Close();
            return Obj;
        }

        private static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(bytes, 0, bytes.Length);
            return bytes;
        }

        private static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
    }
//}

      

        先把集合.ToArray();然后再进行序列化       

       

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值