C# 序列化与反序列化之Binary与Soap无法对泛型List<T>进行序列化的解决方案
C# 序列化与反序列化之Binary与Soap无法对泛型List<T>进行序列化的解决方案
新建Console控制台项目项目,然后添加Team和Person 这2个类,如下:
Team和Person 这2个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace SupremeConsole
{
[Serializable]
public class Team
{ /// <summary>
/// 队名
/// </summary>
public string TName { get; set; } /// <summary>
/// 选手
/// </summary>
public List<Person> PlayerList = new List<Person>();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace SupremeConsole
{
[Serializable]
public class Person
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; } /// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
}
使用Binary或者Soap进行序列化,本例演示使用Soap对类型种的泛型字段进行序列化,代码如下:
using System;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.IO.MemoryMappedFiles;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Runtime.Serialization; namespace SupremeConsole
{
class Program
{
static void Main(string[] args)
{
TestSeri();
Console.ReadLine();
} public static void TestSeri() {
Team team = new Team { TName="",PlayerList = { new Person { Name="",Age=},new Person { Name = "", Age = } } };
#region BinarySerialize 必须添可序列化属性,即要序列化的对象必须添加SerializableAttribute属性,[Serializable]
//string s = SerializeManager.Instance.BinarySerialize<Team>(team);//序列化
//Console.ForegroundColor = ConsoleColor.Green;
//Console.WriteLine("测试序列化成功。。。");
//Console.WriteLine($"测试序列化结果:\r\n{s}"); //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "序列化11111.bin");//序列化
//SerializeManager.Instance.BinarySerialize<Team>(team, path); //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "序列化11111.bin");
//Team test = SerializeManager.Instance.BinaryDeserialize<Team>(path);//反序列化
//if (test != null)
//{
// Console.WriteLine($"测试序列化结果:{test.ToString()}");
//}
#endregion #region SoapSerialize 必须添可序列化属性,即要序列化的对象必须添加SerializableAttribute属性,[Serializable]
string s = SerializeManager.Instance.SoapSerialize<Team>(team);//序列化
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("测试序列化成功。。。");
Console.WriteLine($"测试序列化结果:\r\n{s}"); //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Soap序列化.xml");//序列化
//SerializeManager.Instance.SoapSerialize<Team>(team, path); //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Soap序列化.xml");
//Team test = SerializeManager.Instance.SoapDeserialize<Team>(path);//反序列化
//if (test != null)
//{
// Console.WriteLine($"测试序列化结果:{test.ToString()}");
//}
#endregion
}
/// <summary>
/// Binary泛型序列化
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="t">泛型对象</param>
/// <returns>泛型对象序列化的字符串</returns>
public string BinarySerialize<T>(T t) where T : class
{
string s = null;
try
{
using MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, t);
s = Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
Program.Log.Error($"Binary泛型序列化错误信息:{ex.ToString()}");
}
return s;
} /// <summary>
/// Binary泛型序列化
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="t">泛型对象</param>
/// <param name="path">保存的路径</param>
public void BinarySerialize<T>(T t, string path) where T : class
{
try
{
//string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.txt");
using FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, t);
}
catch (Exception ex)
{
Program.Log.Error($"Binary泛型序列化错误信息:{ex.ToString()}");
}
} /// <summary>
/// Binary泛型的反序列化
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="path">反序列化的序列化文件路径</param>
/// <returns>泛型对象</returns>
public T BinaryDeserialize<T>(string path) where T : class
{
T t = null;
try
{
//string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.txt");
using MemoryStream fs = new MemoryStream(File.ReadAllBytes(path));
BinaryFormatter bf = new BinaryFormatter();
if (bf.Deserialize(fs) is T a)
{
t = a;
}
}
catch (Exception ex)
{
Program.Log.Error($"Binary泛型的反序列化错误信息:{ex.ToString()}");
}
return t;
}
}
}
运行程序报错,错误信息是无法对泛型进行序列化,
第一种解决方式:Soap序列化无法对泛型List<T>进行序列化,解决方法1 :使用[OnSerializing]特性解决泛型List<T>序列化,修改Team为下面代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace SupremeConsole
{
[Serializable]
public class Team
{
#region 初始定义,使用Soap序列化PlayerList会报错,因为Soap序列化无法对泛型List<T>进行序列化,解决方法如下
///// <summary>
///// 队名
///// </summary>
//public string TName { get; set; } ///// <summary>
///// 选手
///// </summary>
//public List<Person> PlayerList = new List<Person>();
#endregion #region Soap序列化无法对泛型List<T>进行序列化,解决方法1 :使用[OnSerializing]特性解决泛型List<T>序列化
/// <summary>
/// 队名
/// </summary>
public string TName { get; set; } Person[] _PlayerArr; /// <summary>
/// 选手
/// </summary>
[NonSerialized] public List<Person> PlayerList = new List<Person>(); [OnSerializing]
public void SetPlayer(StreamingContext sc)
{
_PlayerArr = PlayerList.ToArray();
} [OnDeserialized]
public void SetPlayered(StreamingContext sc)
{
_PlayerArr = null;
} [OnDeserializing]
public void GetPlayer(StreamingContext sc)
{
PlayerList = new List<Person>(_PlayerArr);
} #endregion
}
}
在运行,可以序列化,但是反序列化的时候报错,集合为空错误,那么我们使用第二中解决方法,即实现ISerializable接口,
ISerializable接口中有GetObjectData(SerializationInfo info, StreamingContext context),序列化的时候会调用该方法,可以操作参数SerializationInfo ,SerializationInfo 是一个a name-value dictionary,
反序列化的时候,可以使用构造函数,构造函数的参数和GetObjectData的参数一样,即构造函数(SerializationInfo info, StreamingContext context)。
第二种解决方式:实现ISerializable接口对泛型List<T>进行序列化,修改Team为下面代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace SupremeConsole
{
[Serializable]
public class Team : ISerializable
{
/// <summary>
/// 队名
/// </summary>
public string TName { get; set; } /// <summary>
/// 选手
/// </summary>
public List<Person> PlayerList = new List<Person>(); /// <summary>
/// 序列化的时候会自动调用,使用virtual标记,示方便继承自类的使用
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("TName", TName);
info.AddValue("PlayerList", PlayerList);
} public Team()
{ } /// <summary>
/// 反序了列化的时候自动调用,使用protected标记,示方便继承自类的使用
/// </summary>
protected Team(SerializationInfo info, StreamingContext context)
{
TName = info.GetString("TName");
PlayerList = (List<Person>)info.GetValue("PlayerList",typeof(List<Person>));
}
}
}
再运行程序,可以看到序列化和反序列化都可以了。
其实,Binary与Soap无法对泛型List<T>进行序列化的解决方案,无非就是使用[OnSerializing]特性和实现ISerializable接口,
C# 序列化与反序列化之Binary与Soap无法对泛型List<T>进行序列化的解决方案的更多相关文章
- 初识序列化和反序列化,使用BinaryFormatter类、ISerializable接口、XmlSerializer类进行序列化和反序列化
序列化是将对象转换成字节流的过程,反序列化是把字节流转换成对象的过程.对象一旦被序列化,就可以把对象状态保存到硬盘的某个位置,甚至还可以通过网络发送给另外一台机器上运行的进程.本篇主要包括: ● 使用 ...
- fastjson序列化和反序列化报com.alibaba.fastjson.JSONException: autoType is not support异常问题,解决方案整合
1.问题起因 2017年3月15日,fastjson官方发布安全升级公告,该公告介绍fastjson在1.2.24及之前的版本存在代码执行漏洞,当恶意攻击者提交一个精心构造的序列化数据到服务端时,由于 ...
- .NET Core 对象到字节数组的序列化和反序列化
.NET Core中利用MemoryStream和BinaryFormatter可以实现对象到字节数组的序列化和反序列化: 定义ObjectSerializer类,实现对象到字节数组的序列化和反序列化 ...
- 在C#中,Json的序列化和反序列化的几种方式总结
在这篇文章中,我们将会学到如何使用C#,来序列化对象成为Json格式的数据,以及如何反序列化Json数据到对象. 什么是JSON? JSON (JavaScript Object Notation) ...
- 第一章 JacksonUtil 序列化与反序列化属性总结
1.json-lib与Jackson 关于json-lib与Jackson对比总结如下: 1).性能方面,Jackson的处理能力高出Json-lib10倍左右. 2).json-lib已经停止更新, ...
- php中序列化与反序列化在utf8和gbk编码中测试
在php中如果我们统一编码是没有什么问题了,但是很多朋友会发现一个问题就是utf8和gbk编码中返回的值会有所区别: php 在utf8和gbk编码下使用serialize和unserialize互相 ...
- Java基础18:Java序列化与反序列化
更多内容请关注微信公众号[Java技术江湖] 这是一位阿里 Java 工程师的技术小站,作者黄小斜,专注 Java 相关技术:SSM.SpringBoot.MySQL.分布式.中间件.集群.Linux ...
- JAVA序列化和反序列化XML
package com.lss.utils; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.Bu ...
- Python开发之序列化与反序列化:pickle、json模块使用详解
1 引言 在日常开发中,所有的对象都是存储在内存当中,尤其是像python这样的坚持一切接对象的高级程序设计语言,一旦关机,在写在内存中的数据都将不复存在.另一方面,存储在内存够中的对象由于编程语言. ...
随机推荐
- phpStudy配置多站点多域名和多端口的方法
切记:要想多个域名指向同一个项目,必须将phpstudy的根目录指向你项目所指的地方(原根目录是WWW),修改位置(其他菜单选项 - 软件设置 - 端口常规设置 - 网站目录) 站点:类似于 WWW ...
- 英语hawkbillturtle玳瑁
玳瑁(hawkbillturtle):属爬行纲,海龟科的海洋动物.一般长约0.6米,大者可达1.6米.头顶有两对前额鳞,吻部侧扁,上颚前端钩曲呈鹰嘴状:前额鳞2对:背甲盾片呈覆瓦状排列:背面的角质板覆 ...
- 推荐一些github上的免费好书
本文转载自公众号:跟着小一写bug. 熬夜等于慢性自杀,那熬夜和喜欢的人说话,算不算是慢性殉情? 晚上好 小一来啦 有木有想哀家 其实今晚小一有个拳击课 可是 由于项目明天要演示 调一 ...
- k8s 学习笔记
常用的kubectl命令 kubectl run kubia --image=luksa/kubia --port=8080 --generator=run/v1 --image 指定镜像 - ...
- js 压缩图片 上传
感谢,参考了以下作者的绝大部分内容 https://blog.csdn.net/tangxiujiang/article/details/78755292 https://blog.csdn.net/ ...
- 如何预防SQL注入
归纳一下,主要有以下几点: 1.永远不要信任用户的输入.对用户的输入进行校验,可以通过正则表达式,或限制长度:对单引号和 双"-"进行转换等. 2.永远不要使用动态拼装sql,可以 ...
- K8S概念理解参考
- kali 使用John破解zip压缩包的密码
kali 使用John破解zip压缩包的密码 准备工具: zip压缩包带密码 1个 kali Linux机器 1个 操作步骤: 首先将压缩包上传至kali机器,然后使用zip2joh ...
- BitMap 图片格式与Base64Image格式互转方法
BitMap 图片格式与Base64Image格式互转方法 /// <summary> /// 图片转为base64编码的字符串 /// </summary> /// < ...
- 分析脚本搭建docker环境:python, R
1. 搭建Anaconda Python3.6 FROM nvidia/cuda:8.0-cudnn6-devel-ubuntu16.04 MAINTAINER Tyan <tyan.liu.g ...