C# 如何将数据序列化到本地 数组 对象 等等

来源:互联网 发布:mac安装ie浏览器 编辑:程序博客网 时间:2024/06/07 06:05

1、将需要保存的数据生成json

添加引用: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Web.Extensions.dll

生成json:

 public string ToJSON(object obj)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            return serializer.Serialize(obj);        }

2、将json序列化到本地,即可防止他人偷窥数据

 string fileName = AssemblyOperations.GetAssemblyPath + "\\UserFormula.bat";            Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);            try            {                BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器                binFormat.Serialize(fStream, data);            }            catch (Exception)            {            }            finally            {                fStream.Close();                fStream.Dispose();            }

3、反序列化,即读取

Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);                try                {                    IFormatter binFormat = new BinaryFormatter();//创建二进制序列化器                    binFormat.Binder = new SBinder();                    string jsonStr=binFormat.Deserialize(fStream).ToString();                }                catch (Exception ex)                {                }                finally                {                    fStream.Close();                    fStream.Dispose();                }
4、将json生成对象

 JavaScriptSerializer Serializer = new JavaScriptSerializer();                    List<T> objs = Serializer.Deserialize<List<T>>(jsonStr);

public class SBinder : SerializationBinder    {        public override Type BindToType(string assemblyName, string typeName)        {            Assembly ass = Assembly.GetExecutingAssembly();            return ass.GetType(typeName);        }    }



阅读全文
0 0