Windows Phone 7 Serialization: Binary Serialization

转自:http://www.devdiv.com/forum.php?mod=viewthread&tid=56924&extra=page%3D1%26filter%3Dtypeid%26typeid%3D305%26typeid%3D305

[p=24, null, left]Many of you probably noticed that Windows Phone 7 does not support standard Binary Serialization (using BinaryFormatter from System.Runtime.Serialization namespace), like full version of .NET Framework does, so I have decided to create my own custom solution for Binary serializationand deserialization using BinaryWriter and BinaryReader classes. This post covers my solution partly.

[p=24, null, left]

Additional Information Adding a reference[p=24, null, left]Probably this step could be optional if you decide to modify my code, but currently my approach to Binary serialization requires System.Runtime.Serialization namespace to be added to project for creating a SampleData class described bellow. To add a reference right click the project name and choose Add Reference there. Select System.Runtime.Serialization namespace on .NET tab (check image bellow).

[p=24, null, left] 

Creating a sample classI am going to use almost the same class I’ve created for theDataContract Serialization tutorial. To allow properties to be serialized you have to apply DataMemberAttribute to them.

  1. public class SampleData
  2. {
  3.     [DataMember]
  4.     public string ContentText { get; set; }

  5.     [DataMember]
  6.     public List<int> SomeItems { get; set; }

  7.     public SampleData()
  8.     {
  9.         ContentText = "some text";
  10.         SomeItems = new List<int>() { 1, 2, 3 };
  11.     }
  12. }
复制代码
Creating CustomBinarySerializer class My goal was to make Binary serialization and deserialization look similar to DataContract and XML Serialization , meaning that the should be a constructor that accepts type as parameter and two methods WriteObject and ReadObject. For this reasons I have created CustomBinarySerializer class. Currently, this class handles onlystring and List<int> types (for my SampleData class described above). Feel free to add other handled types and, perhaps, modify this class by creatingextention methods for those types like described inthis article. Partly implemented version of CustomBinarySerializer looks like that (pay attention that this class serialize and deserialize only those properties that are marked withDataMemberAttribute):
  1. public class CustomBinarySerializer
  2. {

  3.     private List<PropertyInfo> serializableProperties = new List<PropertyInfo>();
  4.     private Type serializableObjectType;

  5.     public CustomBinarySerializer(Type objectType)
  6.     {
  7.         serializableObjectType = objectType;
  8.         serializableProperties = GetMarkedProperties(objectType);
  9.     }

  10.     private List<PropertyInfo> GetMarkedProperties(Type type)
  11.     {
  12.         return (from property in type.GetProperties()
  13.                 where property.GetCustomAttributes(true)
  14.                 .Where((x) => x is System.Runtime.Serialization.DataMemberAttribute).Count() > 0
  15.                 select property
  16.                 ).ToList();
  17.     }

  18.     #region Write

  19.     public void WriteObject(Stream stream, object graph)
  20.     {
  21.         if (stream == null || graph == null)
  22.             return;

  23.         BinaryWriter bw = new BinaryWriter(stream);

  24.         foreach (PropertyInfo pi in serializableProperties)
  25.         {
  26.             var value = pi.GetValue(graph, null);

  27.             if (pi.PropertyType == typeof(string))
  28.             {
  29.                 bw.Write(value as string ?? string.Empty);
  30.             }
  31.             else if (pi.PropertyType == typeof(List<int>))
  32.             {
  33.                 WriteIntegerList(bw, value as List<int>);
  34.             }
  35.         }
  36.     }

  37.     private void WriteIntegerList(BinaryWriter bw, List<int> list)
  38.     {
  39.         if (list == null || !list.Any())
  40.         {
  41.             bw.Write(0);
  42.         }
  43.         else
  44.         {
  45.             bw.Write(list.Count);
  46.             list.ForEach(x => bw.Write(x));
  47.         }
  48.     }

  49.     #endregion Write

  50.     #region Read

  51.     public object ReadObject(Stream stream)
  52.     {
  53.         if (stream == null)
  54.             return null;

  55.         BinaryReader br = new BinaryReader(stream);

  56.         object deserializedObject = Activator.CreateInstance(serializableObjectType);

  57.         foreach (PropertyInfo pi in serializableProperties)
  58.         {
  59.             if (pi.PropertyType == typeof(string))
  60.             {
  61.                 pi.SetValue(deserializedObject, br.ReadString(), null);
  62.             }
  63.             else if (pi.PropertyType == typeof(List<int>))
  64.             {
  65.                 pi.SetValue(deserializedObject, ReadIntegerList(br), null);
  66.             }
  67.         }
  68.         return deserializedObject;
  69.     }

  70.     private List<int> ReadIntegerList(BinaryReader br)
  71.     {
  72.         List<int> list = new List<int>();
  73.         int count = br.ReadInt32();

  74.         int index = count;
  75.         while(index > 0){
  76.             list.Add(br.ReadInt32());
  77.             index--;
  78.         }
  79.         return list;
  80.     }

  81.     #endregion Read

  82. }
复制代码

SerializationTo serialize an object you need to create an instance of CustomBinarySerializer class (passing a type of serialized object as an input parameter) and then write serialized data to a stream object using WriteObject method, that accepts stream and object for serialization.
  1. public static void Serialize(Stream streamObject, object objForSerialization)
  2. {
  3.     if (objForSerialization == null || streamObject == null)
  4.         return;

  5.     CustomBinarySerializer ser = new CustomBinarySerializer(objForSerialization.GetType());
  6.     ser.WriteObject(streamObject, objForSerialization);
  7. }
复制代码

DeserializationTo deserialize your object you need to create an instance of CustomBinarySerializer class again (based on a type of serialized object) and then read serialized data using ReadObject method, that accepts an instance of Stream class as parameter.
  1. public static object Deserialize(Stream streamObject, Type serializedObjectType)
  2. {
  3.     if (serializedObjectType == null || streamObject == null)
  4.         return null;

  5.     CustomBinarySerializer ser = new CustomBinarySerializer(serializedObjectType);
  6.     return ser.ReadObject(streamObject);
  7. }
复制代码

TestingYou can use method bellow to test Binary serialization and deserialization. SampleData object after deserialization should be exactly the same as the one before the serialization.
  1. public static void Test()
  2. {
  3.     // serialization
  4.     MemoryStream ms = new MemoryStream();
  5.     BinarySerializationHelper.Serialize(ms, new SampleData());

  6.     ms.Position = 0;

  7.     // deserialization
  8.     var sampleData = BinarySerializationHelper.Deserialize(ms, typeof(SampleData));
  9.     ms.Close();
  10. }
复制代码
Here is how serialized SampleData object looks like during the debug: 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值