c#反序列化
C#序列化(转载)
2011-03-15 | 凯之风 | 转藏(2)
序列化有下列要求:
A> 只序列化PUBLIC的成员变量和属性
B> 类必须有默认识构造函数
C> 如果类没实现自定义序列化(2),那么将按默认方式序列化(1)
D> XmlSerializer不能用于序列化任何实现了IDictionary接口的类的实体,比方说Hashtable。但SoapFormatter和BinaryFormatter没有这个限制。 所以在XML序列化过程中要用[XmlIgnore]标记其不被序列化
1>基本序列化
通过[Serializable]标记,标识该类可序列化
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
1.1序列化成文件
1.1.1 二进制的序列化和反序列化
//序列化
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "一些字符串";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
//反序列化
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(fromStream);
stream.Close();
1.1.2 XML序列化和反序列化
上面的代码换成SoapFormatter即可以生成XML
1.2选择性序列化
[Serializable]
public class MyObject
{
public int n1;
[NonSerialized]
//标记N2不序列化
public int n2;
public String str;
private int n3;
[NonSerialized]//对属性无效
[XmlIgnore]//标记该属性在XML序列化的过程中不序列化
public int N3
{
get{return n3;}
set{n3=value;}
}
}
注意:当类成员变量中出现不能被序列化的类或接口时候我们要通过
[NonSerialized] 只针对成员变量
[XmlIgnore] 针对成员变量和属性,只针对XML序列化
标记其不被序列化和反序列化
特别注意:要使某属性在XML序列化过程中不被序列化只能使用[XmlIgnore],[NonSerialized]无效
2>自定义序列化
为了解决1中序列化过程中会出现某些成员变量序列化过程中数据丢失的显现,
可采用自定义的序列化
[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;
public MyObject()
{
}
protected MyObject(SerializationInfo info, StreamingContext context)
{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}
其派生类也必须实现上面的接口方法
[Serializable]
public class ObjectTwo : MyObject
{
public int num;
public ObjectTwo() : base()
{
}
protected ObjectTwo(SerializationInfo si, StreamingContext context) : base(si,context)
{
num = si.GetInt32("num");
}
public override void GetObjectData(SerializationInfo si, StreamingContext context)
{
base.GetObjectData(si,context);
si.AddValue("num", num);
}
}
切记要在反序列化构造函数中调用基类,否则,将永远不会调用基类上的构造函数,并且在反序列化后也无法构建完整的对象。
3>WEB 服务中的序列化
WEB 服务返回对象时候会自动把该对象进行XML序列化
因此,一个类要想在WEB 服务上传递必须可XML序列化
public class Test : WebService {
[WebMethod()]
public DateTime EchoString([XmlElement(DataType="string")]
string strval) {
return DateTime.Now;
}
//通过XmlInclude声明序列化过程中相关的类信息
[WebMethod()]
[XmlInclude(typeof(Car)), XmlInclude(typeof(Bike))]
public Vehicle Vehicle(string licenseNumber) {
if (licenseNumber == "0") {
Vehicle v = new Car();
v.licenseNumber = licenseNumber;
return v;
}
else if (licenseNumber == "1") {
Vehicle v = new Bike();
v.licenseNumber = licenseNumber;
return v;
}
else {
return null;
}
}
}
//通过XmlRoot指定序列化的ROOT描述信息
[XmlRoot("NewVehicle")]
public abstract class Vehicle {
public string licenseNumber;
public DateTime make;
}
public class Car : Vehicle {
}
public class Bike : Vehicle {
}
4>两个通用的序列化函数------来自Enterprise Lib 配置模块
public override object Serialize(object value)
{
XmlSerializer xmlSerializer = CreateXmlSerializer(value.GetType());
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
XmlDocument doc = new XmlDocument();
try
{
xmlTextWriter.WriteStartElement("xmlSerializerSection");
xmlTextWriter.WriteAttributeString("type", value.GetType().AssemblyQualifiedName);
xmlSerializer.Serialize(xmlTextWriter, value);
xmlTextWriter.WriteEndElement();
xmlTextWriter.Flush();
doc.LoadXml(stringWriter.ToString());
}
finally
{
xmlTextWriter.Close();
stringWriter.Close();
}
return doc.DocumentElement;
}
public override object Deserialize(object section)
{
XmlNode sectionNode = (XmlNode)section;
XmlNode serializationNode = sectionNode.SelectSingleNode("//xmlSerializerSection");
if (serializationNode == null)
{
throw new ConfigurationException(SR.ExceptionNotInSerializedObj);
}
XmlAttribute typeAttribute = serializationNode.Attributes["type"];
if (typeAttribute == null)
{
throw new ConfigurationException(SR.ExceptionSerializationTypeMissing);
}
string typeName = typeAttribute.Value;
Type classType = null;
try
{
classType = Type.GetType(typeName, true);
}
catch (TypeLoadException ex)
{
throw new ConfigurationException(SR.ExceptionTypeCreateError(typeName), ex);
}
catch (FileNotFoundException ex)
{
throw new ConfigurationException(SR.ExceptionTypeCreateError(typeName), ex);
}
if (serializationNode.ChildNodes.Count == 0)
{
throw new ConfigurationException(SR.ExceptionSerializedObjectMissing);
}
XmlSerializer xs = CreateXmlSerializer(classType);
try
{
return xs.Deserialize(new XmlNodeReader(serializationNode.ChildNodes[0]));
}
catch (InvalidOperationException e)
{
string message = e.Message;
if (null != e.InnerException)
{
message = String.Concat(message, " ", e.InnerException.Message);
}
throw new ConfigurationException(message, e);
}
}
c#反序列化的更多相关文章
- C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素”
Q: 在反序列化 Xml 字符串为 Xml 对象时,抛出如下异常. 即在 XML文档(0, 0)中有一个错误:缺少根元素. A: 首先看下代码: StringBuilder sb = new Stri ...
- C# 序列化与反序列化几种格式的转换
这里介绍了几种方式之间的序列化与反序列化之间的转换 首先介绍的如何序列化,将object对象序列化常见的两种方式即string和xml对象; 第一种将object转换为string对象,这种比较简单没 ...
- 迟来的Json反序列化
源码发布 搞了一个下午,终于搞定了这个号称中国的github...以后源码直接在这里发布了(github实在用不来,英文实在太烂了) https://code.csdn.net/jy02305022/ ...
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...
- 使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)
在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合.字典.动态对象和匿名对象 ...
- 【.NET深呼吸】如何反序列化动态JSON
.net本身除了支持SOAP.XML.二进制等序列化和反序列化,后来也加入了对JSON的序列化的支持.然而,在实际开发中,常常会遇到结构不确定的JSON对象,这些对象可能是其他代码动态生成的,你事先无 ...
- Java 序列化与反序列化
1.什么是序列化?为什么要序列化? Java 序列化就是指将对象转换为字节序列的过程,而反序列化则是只将字节序列转换成目标对象的过程. 我们都知道,在进行浏览器访问的时候,我们看到的文本.图片.音频. ...
- C#中怎样实现序列化和反序列化
我们想要将数据进行持久化的操作的话,也就是将数据写入到文件中,我们在C#中可以通过IO流来操作,同时也可以通过序列化来操作,本人是比较推荐使用序列化操作的 因为我们如果想要将一个对象持久化到文件中 如 ...
- Java序列化与反序列化
Java序列化与反序列化是什么?为什么需要序列化与反序列化?如何实现Java序列化与反序列化?本文围绕这些问题进行了探讨. 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列 ...
- 让Visual Studio 2013为你自动生成XML反序列化的类
Visual Sutdio 2013增加了许多新功能,其中很多都直接提高了对代码编辑的便利性.如: 1. 在代码编辑界面的右侧滚动条上显示不同颜色的标签,让开发人员可以对所编辑文档的修改.查找.定位情 ...
随机推荐
- @ManyToMany中间表附加字段设计
在使用@ManyToMany时,若中间表只有相应的外键字段可以直接建立两个对应的Entity 设置ManyToMany @ManyToMany 两个表多对多关联 但若是中间表有自己的附加字段,这需要为 ...
- Asp.net主题(theme)和皮肤(skin)的使用
asp.net 的服务器端控件提供了多种样式的设计,如果对每个控件都单独设置,是比较繁琐的事情,所以微软也提供了针对这些服务器端控件的样式管理,其实也可以通过 css来控制部分服务器端控件的样式,比如 ...
- U3D Trigger事件触发
使用Trigger事件触发,可以达到虽然触发了,可是不改变任何效果. 这个是进入时候触发的: void OnTriggerEnter2D(Collider2D other) { print (othe ...
- TFS 服务器更换后工作区无法绑定
需要删除工作区,删除命令如下 tf workspace /delete 工作区名;创建的用户 /server:TFS服务器 例 tf workspace /delete WHQ-PC;whq /ser ...
- OpenGL ES 3.0 点,线,三角形绘制形式总结
OpenGL ES 3.0 顶点 -1, 1, 0, -0.5f, 0, 0, 0, -1, 0, -1, 0, 0, 0.5f, 0, 0, 1, -1, ...
- Android 官方新手指导教程
一.开始 1.建立第一个应用程序 依赖关系和先决条件 Android SDK ADT Plugin 20.0.0 或更高 (如果你使用eclipse的话) 欢迎来到Android应用程序开发! 这一节 ...
- NSNumber 转 NSString
之前number 转string时候调用stringValue,后来发现未完全转 NSNumber * a_num = [NSNumber numberWithInteger: ]; NSString ...
- javascript事件详解1
事件流讲解来袭,嘎嘎嘎嘎嘎 ---------------------------------------------------------------- 1.事件流:描述的是在页面中接受事件的顺序 ...
- Jquery实现图片左右滚动(自动)
<!DOCTYPE HTML><html><head><title>基于jQuery的控制左右滚动效果_自动滚动版本</title>< ...
- wdcp-apache配置错误导致进程淤积进而内存吃紧
内存总是越来越少,虚拟内存使用越来越多 首先确定到底是什么占用了大量的内存 可以看到,大部分内存被闲置的httpd进程占用 且当我重启mysql服务后,内存没有出现明显变化,但是当我重启apache时 ...