C#序列化反序列化对象为base64字符串

梦想游戏人
目录:
C#
之所以序列化为base64 字符串 方便传输,可存储在本地 也可以是服务器
 public class Serializer
    {
        private Serializer() { }
        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)
            {
                Debug.LogError(" Serialize error   " + ex.Message);
                return null;
            }
        }
        public static T Deserialize<T>(string str)
        {
            T obj = default(T);
            try
            {
                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)
            {
                Debug.LogError(" Serialize error   " + ex.Message);
                return obj;
            }
            return obj;
        }
        //将一组array 对象 序列化为 基于base64的存储string
        public static string SerializeMulti<T>(IEnumerable objs)
        {
            string ser_str = "";
            foreach (T data in objs)
            {
                string str = Serialize<T>(data);
                ser_str += str + SPLIT_FLAG_BASE64;
            }
            return ser_str;
        }
        //从 字符串 反序列化出对象数组
        public static ArrayList DeserializeMulti<T>(string ser_str) where T : new()
        {
            ArrayList ret = new ArrayList();

            if (string.IsNullOrEmpty(ser_str))
            {
                return ret;
            }
            string[] strs = ser_str.Split(SPLIT_FLAG_BASE64);
            if (strs.Length <= 0) return ret;

            foreach (string s in strs)
            {
                if (string.IsNullOrEmpty(s)) continue;
                var obj = Deserialize<T>(s);
                ret.Add(obj);
            }
            return ret;
        }
        public const char SPLIT_FLAG_BASE64 = (char)111;//base64 生成的间隔标识符数值 只要不是base64 生成的char 都可以当做间隔符
    }
Scroll Up