序列化/反序列化为字符串C#

前端之家收集整理的这篇文章主要介绍了序列化/反序列化为字符串C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
第一次玩C#中的序列化…任何帮助将不胜感激!
以下是我的通用序列化器和反序列化器:
  1. public static string SerializeObject<T>(T objectToSerialize)
  2. {
  3. BinaryFormatter bf = new BinaryFormatter();
  4. MemoryStream memStr = new MemoryStream();
  5.  
  6. try
  7. {
  8. bf.Serialize(memStr,objectToSerialize);
  9. memStr.Position = 0;
  10.  
  11. return Convert.ToBase64String(memStr.ToArray());
  12. }
  13. finally
  14. {
  15. memStr.Close();
  16. }
  17. }
  18.  
  19. public static T DeserializeObject<T>(string str)
  20. {
  21. BinaryFormatter bf = new BinaryFormatter();
  22. byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
  23. MemoryStream ms = new MemoryStream(b);
  24.  
  25. try
  26. {
  27. return (T)bf.Deserialize(ms);
  28. }
  29. finally
  30. {
  31. ms.Close();
  32. }
  33. }

这是我尝试序列化的对象:

  1. [Serializable()]
  2. class MatrixSerializable : ISerializable
  3. {
  4. private bool markerFound;
  5. private Matrix matrix;
  6.  
  7. public MatrixSerializable( Matrix m,bool b)
  8. {
  9. matrix = m;
  10. markerFound = b;
  11. }
  12.  
  13. public MatrixSerializable(SerializationInfo info,StreamingContext ctxt)
  14. {
  15. markerFound = (bool)info.GetValue("markerFound",typeof(bool));
  16.  
  17. matrix = Matrix.Identity;
  18.  
  19. if (markerFound)
  20. {
  21.  
  22. //deserialization code
  23. }
  24. }
  25.  
  26. public void GetObjectData(SerializationInfo info,StreamingContext ctxt)
  27. {
  28. // serialization code
  29. }
  30.  
  31. public Matrix Matrix
  32. {
  33. get { return matrix; }
  34. set { matrix = value; }
  35. }
  36.  
  37. public bool MarkerFound
  38. {
  39. get { return markerFound; }
  40. set { markerFound = value; }
  41. }
  42. }

以及如何运行它的示例:

  1. MatrixSerializable ms = new MatrixSerializable(Matrix.Identity * 5,true);
  2.  
  3. string s = Serializer.SerializeObject<MatrixSerializable>(ms);
  4.  
  5. Console.WriteLine("serialized: " + s);
  6.  
  7. ms = Serializer.DeserializeObject<MatrixSerializable>(s);
  8.  
  9. Console.WriteLine("deserialized: " + ms.Matrix + " " + ms.MarkerFound);

当我尝试运行它时,我得到一个错误“SerializationException未处理:输入流不是有效的二进制格式.起始内容(以字节为单位)是:41-41-45-41-41-41-44-2F- 2F-2F-2F-2F-41-51-41-41-41 ……“

关于我做错了什么或如何解决这个问题的任何建议将不胜感激!

解决方法

您正在使用Base64将字节数组转换为字符串,并使用GetUtf8字节将字符串转换回字节数组.

替换System.Text.Encoding.UTF8.GetBytes(str);与Convert.FromBase64String(str);

猜你在找的C#相关文章