c#序列化反序列化工具(json,binary,xml)
Posted 海之殇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#序列化反序列化工具(json,binary,xml)相关的知识,希望对你有一定的参考价值。
using System; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Json; namespace weekReportPlan { public static class SerializeHelper { /// <summary> /// 将一个对象序列化为字节(byte)数组 /// </summary> /// <param name="t"></param> /// <returns></returns> public static byte[] Serialize(this object t) { MemoryStream stream = new MemoryStream(); BinaryFormatter former = new BinaryFormatter(); former.Serialize(stream, t); return stream.GetBuffer(); } /// <summary> /// 将字节(byte)数组 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="b"></param> /// <returns></returns> public static T DeserializeTo<T>(this byte[] b) { BinaryFormatter bFormatter = new BinaryFormatter(); return (T)bFormatter.Deserialize(new MemoryStream(b)); } /// <summary> /// Json序列化 /// </summary> public static string ToJsJson(this object item) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } /// <summary> /// Json反序列化 /// </summary> public static T FromJsonTo<T>(this string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T jsonObject = (T)ser.ReadObject(ms); ms.Close(); return jsonObject; } /// <summary> /// 将一个对象序列化为字节(byte)数组并保存到指定文件路径 /// </summary> /// <param name="t"></param> /// <param name="path"></param> public static void SerializeToFile(this object t,string path) { using (FileStream fs = new FileStream(path, FileMode.Create)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, t); } } /// <summary> /// 从指定文件路径中读取数据并反序列化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path"></param> /// <returns></returns> public static T DeserializeFromFileTo<T>(string path) { T t; using (FileStream fs = new FileStream(path, FileMode.Open)) { BinaryFormatter bf = new BinaryFormatter(); t = (T)bf.Deserialize(fs); } return t; } } }
注意1:序列化为二进制的时候需要在类中添加[Serializable]特性
注意2:如果类添加了[Serializable]特性,并且属性都是自动属性时,将该类对象序列化为json的时候需要给类再添加[DataContract]特性,给类属性添加[DataMember]特性
以上是关于c#序列化反序列化工具(json,binary,xml)的主要内容,如果未能解决你的问题,请参考以下文章