c#各种序列化方式

来源:互联网 发布:网址域名注册 编辑:程序博客网 时间:2024/05/17 01:51

序列化Json数据和反序列化

public static string GetJson<T>(T obj)        {            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());            using (MemoryStream stream = new MemoryStream())            {                json.WriteObject(stream, obj);                return Encoding.UTF8.GetString(stream.ToArray());            }        }        public static T ParseFromJson<T>(string szJson)        {            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))            {                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));                return (T)serializer.ReadObject(ms);            }        }

序列化Json数据和反序列化,方法二,使用JavaScriptSerializer

 public static List<T> JSONStringToList<T>(string JsonStr)        {            JavaScriptSerializer Serializer = new JavaScriptSerializer();            List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);            return objs;        }


把实体序列化成字节流保存至文本,和从文本中反序列化

 FileStream serializationStream = null;string filePath = String.Format("{0}/{1}.txt",sPath, Time.ToString("yyyyMMddHHmmss"));serializationStream = new FileStream(filePath, FileMode.OpenOrCreate);BinaryFormatter formatter = new BinaryFormatter();object readdata = (object)formatter.Deserialize(serializationStream);serializationStream.Close();

//序列化 object obj = new object();                        MemoryStream memoryStream = new MemoryStream();                        BinaryFormatter formatter1 = new BinaryFormatter();                        formatter1.Serialize(memoryStream, obj);                        byte[] buffer1 = memoryStream.ToArray();                        memoryStream.Close();




0 0
原创粉丝点击