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这样的坚持一切接对象的高级程序设计语言,一旦关机,在写在内存中的数据都将不复存在.另一方面,存储在内存够中的对象由于编程语言. ...
随机推荐
- Java开发环境之Svn
查看更多Java开发环境配置,请点击<Java开发环境配置大全> 拾肆章:Svn安装教程 1)去官网下载TortoiseSVN安装包 https://tortoisesvn.net/ 2) ...
- k8s创建harbor私有镜像仓库
1. 部署准备 准备harbor软件包 在部署节点上: mv harbor-offline-installer-v1.4.0.tgz /opt/ && cd /opt tar zxvf ...
- JavaFX 学生登陆表格
利用JavaFX实现一个学生登陆的界面,其中包括各种JavaFX组件的使用,利用焦点变动自动检测内容的合法性和监控文本输入以及页面的跳转,具体代码如下: /* * To change this lic ...
- eclipse使用mybatis实现Java与xml文件相互跳转
原文:https://jingyan.baidu.com/article/8ebacdf0f06c8c09f65cd5a0.html 一直习惯使用eclipse,看见同事使用IDEA,直接从Java类 ...
- The 2016 ACM-ICPC Asia China-Final D. Ice Cream Tower 二分 + 贪心
题目大意: 对于给出的n个冰激凌球的大小,满足下面的球的大小是上一个的至少2倍,对于给出的k(由k的冰激凌球才能算作一个冰激凌塔),问n个冰激凌球可以最多堆出多少个高度为k的冰激凌塔 题目分析: 对于 ...
- django项目中使用KindEditor富文本编辑器。
先从官网下载插件,放在static文件下 前端引入 <script type="text/javascript" src="/static/back/kindedi ...
- 王天悦 201671030121 实验十四 团队项目评审&课程学习总结
项目 内容 课程名称 2016级计算机科学与工程学院软件工程(西北师范大学) 作业要求 实验十四 团队项目评审&课程学习总结 课程学习目标 (1)掌握软件项目评审会流程,(2)反思总结课程学习 ...
- Easyui combobox 源码修改模糊查询v=1.34
原来的匹配方式: $.fn.combobox.defaults=$.extend({},$.fn.combo.defaults,{valueField:"value",textFi ...
- 利用requests库访问网站
1.关于requests库 函数 Response对象包含服务器返回的所有信息,也包含请求的Request信息. 访问百度二十次 import requests def getHTMLText(url ...
- List的复制 (浅拷贝与深拷贝)
开门见山的说,List的复制其实是很常见的,List其本质就是数组,而其存储的形式是地址 如图所示,将List A列表复制时,其实相当于A的内容复制给了B,java中相同内容的数组指向同一地址,即进行 ...