Table of Contents
一、问题重现
二、问题分析
三、解决方案一:通过控制属性反序列化顺序
四、解决方案二:将数据成员定义在字段上而不是属性上
总结
Home Database Mysql Tutorial 一个关于解决序列化问题的编程技巧

一个关于解决序列化问题的编程技巧

Jun 07, 2016 pm 03:10 PM
about Serialization article Programming skills solve

在前一篇文章中我曾经说过,现在正在做一个小小的框架以实现采用统一的API实现对上下文(Context)信息的统一管理。这个框架同时支持Web和GUI应用,并支持跨线程传递和跨域传递(这里指在WCF服务调用中实现客户端到服务端隐式传递),以及对上下文项目(Cont

在前一篇文章中我曾经说过,现在正在做一个小小的框架以实现采用统一的API实现对上下文(Context)信息的统一管理。这个框架同时支持Web和GUI应用,并支持跨线程传递和跨域传递(这里指在WCF服务调用中实现客户端到服务端隐式传递),以及对上下文项目(ContextItem)的读写控制。关键就在于后面两个特性的支持上面,出现一个小小的关于序列化的问题。解决方案只需要改动短短的一行代码,结果却让我折腾了老半天。

一、问题重现

为了重现我实际遇到的问题,我特意将问题简化,为此我写了一个简单的例子(你可以从这里下载)。在下面的代码片断中,我创建了一个名称为ContextItem的类型,代表一个需要维护的上下文项。由于需要在WCF服务调用实现自动传递,我将起定义成DataContract。ContextItem包含Key,Value和ReadOnly三个属性,不用说ReadOnly表示该ContextItem可以被修改。注意Value属性Set方法的定义——如果ReadOnly则抛出异常。

<span>   1:</span> [DataContract(Namespace = <span>"http://www.artech.com"</span>)]
Copy after login
Copy after login
Copy after login
<span>   2:</span> <span>public</span> <span>class</span> ContextItem
Copy after login
Copy after login
Copy after login
<span>   3:</span> {
Copy after login
Copy after login
Copy after login
<span>   4:</span>     <span>private</span> <span>object</span> <span>value</span> = <span>null</span>;
Copy after login
Copy after login
<span>   5:</span>     [DataMember]
Copy after login
<span>   6:</span>     <span>public</span> <span>string</span> Key { get; <span>private</span> set; }
Copy after login
<span>   7:</span>     [DataMember]
Copy after login
<span>   8:</span>     <span>public</span> <span>object</span> Value
Copy after login
<span>   9:</span>     {
Copy after login
<span>  10:</span>         get
Copy after login
<span>  11:</span>         {
Copy after login
<span>  12:</span>             <span>return</span> <span>this</span>.<span>value</span>;
Copy after login
<span>  13:</span>         }
Copy after login
<span>  14:</span>         set
Copy after login
<span>  15:</span>         {
Copy after login
<span>  16:</span>             <span>if</span> (<span>this</span>.ReadOnly)
Copy after login
<span>  17:</span>             {
Copy after login
<span>  18:</span>                 <span>throw</span> <span>new</span> InvalidOperationException(<span>"Cannot change the value of readonly context item."</span>);
Copy after login
<span>  19:</span>             }
Copy after login
<span>  20:</span>             <span>this</span>.<span>value</span> = <span>value</span>;
Copy after login
<span>  21:</span>         }
Copy after login
<span>  22:</span>     }
Copy after login
<span>  23:</span>     [DataMember]
Copy after login
<span>  24:</span>     <span>public</span> <span>bool</span> ReadOnly { get; set; }
Copy after login
<span>  25:</span>     <span>public</span> ContextItem(<span>string</span> key, <span>object</span> <span>value</span>)
Copy after login
<span>  26:</span>     {
Copy after login
<span>  27:</span>         <span>if</span> (<span>string</span>.IsNullOrEmpty(key))
Copy after login
<span>  28:</span>         {
Copy after login
<span>  29:</span>             <span>throw</span> <span>new</span> ArgumentNullException(<span>"key"</span>);
Copy after login
<span>  30:</span>         }
Copy after login
<span>  31:</span>         <span>this</span>.Key = key;
Copy after login
<span>  32:</span>         <span>this</span>.Value = <span>value</span>;
Copy after login
<span>  33:</span>     }
Copy after login
<span>  34:</span> }
Copy after login

为了演示序列化和反序列化,我写了如下两个静态的帮助方法。Serialize和Deserialize分别用于序列化和反序列化,前者将对象序列成成XML并保存到指定的文件中,后者则从文件读取XML并反序列化成相应的对象。

<span>   1:</span> <span>public</span> <span>static</span> T Deserialize<t>(<span>string</span> fileName)</t>
Copy after login
<span>   2:</span> {
Copy after login
Copy after login
<span>   3:</span>     DataContractSerializer serializer = <span>new</span> DataContractSerializer(<span>typeof</span>(T));
Copy after login
<span>   4:</span>     <span>using</span> (XmlReader reader = <span>new</span> XmlTextReader(fileName))
Copy after login
<span>   5:</span>     {
Copy after login
<span>   6:</span>         <span>return</span> (T)serializer.ReadObject(reader);
Copy after login
<span>   7:</span>     }
Copy after login
<span>   8:</span> }
Copy after login
<span>   9:</span>  
Copy after login
<span>  10:</span> <span>public</span> <span>static</span> <span>void</span> Serialize<t>(T instance, <span>string</span> fileName)</t>
Copy after login
<span>  11:</span> {
Copy after login
<span>  12:</span>     DataContractSerializer serializer = <span>new</span> DataContractSerializer(<span>typeof</span>(T));
Copy after login
<span>  13:</span>     <span>using</span> (XmlWriter writer = <span>new</span> XmlTextWriter(fileName, Encoding.UTF8))
Copy after login
<span>  14:</span>     {
Copy after login
<span>  15:</span>         serializer.WriteObject(writer, instance);
Copy after login
<span>  16:</span>     } 
Copy after login
<span>  17:</span>     Process.Start(fileName);
Copy after login
<span>  18:</span> }
Copy after login

我们的程序很简单。从如下的代码片断中,我们先创建一个ContextItem对象,然后将ReadOnly属性设置成true。然后调用Serialize方法将对象序列化成XML并保存在一个名称为context.xml的文件中。然后调用Deserialize方法,读取该文件进行反序列化。

<span>   1:</span> <span>static</span> <span>void</span> Main(<span>string</span>[] args)
Copy after login
<span>   2:</span> {
Copy after login
Copy after login
<span>   3:</span>     var contextItem1 = <span>new</span> ContextItem(<span>"__userId"</span>, <span>"Foo"</span>);
Copy after login
<span>   4:</span>     contextItem1.ReadOnly = <span>true</span>;
Copy after login
<span>   5:</span>     Serialize<contextitem>(contextItem1, <span>"context.xml"</span>);</contextitem>
Copy after login
<span>   6:</span>     var contextItem2 = Deserialize<contextitem>(<span>"context.xml"</span>);           </contextitem>
Copy after login
<span>   7:</span> }
Copy after login

序列化操作能够正常执行,但当程序执行到Deserialize的时候抛出如下一个InvalidOperationException异常。

一个关于解决序列化问题的编程技巧

二、问题分析

从上面给出的截图,我们不难看出,异常是在给ContextItem对象的Value属性赋值的时候抛出的。如果对DataContractSerializer序列化器的序列化/反序列化规则的有所了解的话,应该知道:对于数据契约(DataContract)基于属性(Property)的数据成员(DataMember),序列器在反序列化的时候是通过调用Set方法对其进行初始化的。在本例中,由于ReadOnly是True,在对Value进行反序列化的时候必然会调用Set方法。但是,只读的ContextItem却不能对其赋值,所以异常抛出。

那么,如何来解决这个问题呢?我最初的想法是这样:在序列化的时候将ReadOnly属性设置成False,然后添加另一个属性专门用于保存真实的值。在进行反序列的时候,由于ReadOnly为false,所以不会出现异常。当反序列化完成之后,在将ReadOnly的初始值赋上。虽然上述的方案能够解决问题,但是为此对ContextItem添加一个只在序列化和反序列化的过程中在有用的属性,总觉得很丑陋。

我们不妨换一种思路:异常产生于对Value属性凡序列化时发现ReadOnly非True的情况。那么怎样采用避免这种情况的发生呢?如果Value属性先于ReadOnly属性被序列化,那么ReadOnly的初始值就是False,这个问题不就解决了吗?这就是我们的第一个解决方案。

三、解决方案一:通过控制属性反序列化顺序

那么,如果控制那么属性先被反序列化,那么后被序列化呢?这就是要了解DataContractSerializer序列化器的序列化和发序列化规则了。在默认的情况下,DataContractSerializer是按照数据成员的名称的顺序进行序列化的。这可以从生成出来的XML的结构看出来。而XML元素的先后顺序决定了反序列化的顺序。

<span>   1:</span> <span><span>ContextItem</span> <span>xmlns:i</span><span>="http://www.w3.org/2001/XMLSchema-instance"</span> <span>xmlns</span><span>="http://www.artech.com"</span><span>></span></span>
Copy after login
<span>   2:</span>     <span><span>Key</span><span>></span>__userId<span></span><span>Key</span><span>></span></span>
Copy after login
<span>   3:</span>     <span><span>ReadOnly</span><span>></span>true<span></span><span>ReadOnly</span><span>></span></span>
Copy after login
<span>   4:</span>     <span><span>Value</span> <span>xmlns:d2p1</span><span>="http://www.w3.org/2001/XMLSchema"</span> <span>i:type</span><span>="d2p1:string"</span><span>></span>Foo<span></span><span>Value</span><span>></span></span>
Copy after login
<span>   5:</span> <span></span><span>ContextItem</span><span>></span>
Copy after login

在上面的例子中,ContextItem的ReadOnly排在Value的前面,会先被序列化。那么,是不是我们要更新Value或者ReadOnly的数据成员(DataMember,不是属性名称)呢?这肯定不是我们想要的解决方案。在SOA的世界中,DataMember是契约的一部分,往往是不容许更改的。

如果在不更改数据成员名称的前提下让属性Value先于ReadOnly被序列化,需要用到DataContractSerializer另一条反序列化规则:我们可以通过DataMemberAttribute特性的Order属性控制序列化后的属性在XML元素列表中的位置。

为此,我们有了答案,我们只需要将ContextItem稍加改动就可以了。在如下的代码中,在为Value和ReadOnly两个属性应用DataMemberAttribute的时候,将Order属性分别设置成1和2,这样就能使ContextItem对象在被序列化的时候,Value和ReadOnly属性对应的XML元素将永远会有前后之分。这里还需要注意的是,在Value属性的Set方法中,判断是否只读,采用的不是ReadOnly属性,而是对应的readonly字段。这一点非常重要,如果调用ReadOnly属性将会迫使该属性被反序列化。

<span>   1:</span> [DataContract(Namespace = <span>"http://www.artech.com"</span>)]
Copy after login
Copy after login
Copy after login
<span>   2:</span> <span>public</span> <span>class</span> ContextItem
Copy after login
Copy after login
Copy after login
<span>   3:</span> {
Copy after login
Copy after login
Copy after login
<span>   4:</span>     <span>private</span> <span>object</span> <span>value</span> = <span>null</span>;
Copy after login
Copy after login
<span>   5:</span>     <span>private</span> <span>bool</span> readOnly;
Copy after login
<span>   6:</span>     [DataMember]
Copy after login
<span>   7:</span>     <span>public</span> <span>string</span> Key { get; <span>private</span> set; }
Copy after login
<span>   8:</span>  
Copy after login
<span>   9:</span>     [DataMember(Order = 1)]
Copy after login
<span>  10:</span>     <span>public</span> <span>object</span> Value
Copy after login
<span>  11:</span>     {
Copy after login
<span>  12:</span>         get
Copy after login
<span>  13:</span>         {
Copy after login
<span>  14:</span>             <span>return</span> <span>this</span>.<span>value</span>;
Copy after login
<span>  15:</span>         }
Copy after login
<span>  16:</span>         set
Copy after login
<span>  17:</span>         {
Copy after login
<span>  18:</span>             <span>if</span> (<span>this</span>.readOnly)
Copy after login
<span>  19:</span>             {
Copy after login
<span>  20:</span>                 <span>throw</span> <span>new</span> InvalidOperationException(<span>"Cannot change the value of readonly context item."</span>);
Copy after login
<span>  21:</span>             }
Copy after login
<span>  22:</span>             <span>this</span>.<span>value</span> = <span>value</span>;
Copy after login
<span>  23:</span>         }
Copy after login
<span>  24:</span>     }
Copy after login
<span>  25:</span>     [DataMember(Order =2)]
Copy after login
<span>  26:</span>     <span>public</span> <span>bool</span> ReadOnly
Copy after login
<span>  27:</span>     {
Copy after login
<span>  28:</span>         get
Copy after login
<span>  29:</span>         {
Copy after login
<span>  30:</span>             <span>return</span> readOnly;
Copy after login
<span>  31:</span>         }
Copy after login
<span>  32:</span>         set
Copy after login
<span>  33:</span>         {
Copy after login
<span>  34:</span>             readOnly = <span>value</span>;
Copy after login
<span>  35:</span>         }
Copy after login
<span>  36:</span>     }
Copy after login
<span>  37:</span>     <span>//Others</span>
Copy after login
<span>  38:</span> }
Copy after login

有兴趣的读者可以亲自试试看,如果我们进行了如上的更改,前面的程序就能正常运行了。到这里,有的读者可以要问了,你不是说仅仅有一行代码的变化吗,我看上面改动的不止一行嘛。没有错,我们完全可以作更少的更改来解决问题。

四、解决方案二:将数据成员定义在字段上而不是属性上

我们再换一种思维,之所以出现异常是在反序列化的时候调用Value属性的Set方法所致。如果在反序列化的时候不调用这个方法不就得了吗?那么,如何才能避免对Value属性的Set方法的调用呢?方法很简单,那就是将数据成员定义在字段上,而不是属性上。基于属性的数据成员在反序列化的时候不得不通过调用Set方法对数据项进行初始化,而基于字段的数据成员在反序列化的时候只需要直接对其复制就可以了。

基于这样的思路,我们对原来的ContextItem进行简单的改动——将DataMemberAttribute特性从Value属性移到value字段上。需要注意的,为了符合于原来的Schema,需要将DataMemberAttribute特性的Name属性设置成“Value”。

<span>   1:</span> [DataContract(Namespace = <span>"http://www.artech.com"</span>)]
Copy after login
Copy after login
Copy after login
<span>   2:</span> <span>public</span> <span>class</span> ContextItem
Copy after login
Copy after login
Copy after login
<span>   3:</span> {
Copy after login
Copy after login
Copy after login
<span>   4:</span>     [DataMember]
Copy after login
<span>   5:</span>     <span>public</span> <span>string</span> Key { get; <span>private</span> set; }
Copy after login
<span>   6:</span>  
Copy after login
<span>   7:</span>     [DataMember(Name = <span>"Value"</span>)]
Copy after login
<span>   8:</span>     <span>private</span> <span>object</span> <span>value</span> = <span>null</span>;
Copy after login
<span>   9:</span>     <span>public</span> <span>object</span> Value
Copy after login
<span>  10:</span>     {
Copy after login
<span>  11:</span>         get
Copy after login
<span>  12:</span>         {
Copy after login
<span>  13:</span>             <span>return</span> <span>this</span>.<span>value</span>;
Copy after login
<span>  14:</span>         }
Copy after login
<span>  15:</span>         set
Copy after login
<span>  16:</span>         {
Copy after login
<span>  17:</span>             <span>if</span> (<span>this</span>.ReadOnly)
Copy after login
<span>  18:</span>             {
Copy after login
<span>  19:</span>                 <span>throw</span> <span>new</span> InvalidOperationException(<span>"Cannot change the value of readonly context item."</span>);
Copy after login
<span>  20:</span>             }
Copy after login
<span>  21:</span>             <span>this</span>.<span>value</span> = <span>value</span>;
Copy after login
<span>  22:</span>         }
Copy after login
<span>  23:</span>     }
Copy after login
<span>  24:</span>     [DataMember]
Copy after login
<span>  25:</span>     <span>public</span> <span>bool</span> ReadOnly { get; set; }     
Copy after login
<span>  26:</span>      <span>//Others</span>
Copy after login
<span>  27:</span>     }
Copy after login
<span>  28:</span> }
Copy after login

总结

虽然这仅仅是一个很小的问题,解决的方案看起来也是如此的简单。但是,这并不意味着这是一个可以被忽视的问题,背后隐藏对DataMemberAttribute序列化的序列化规则的理解。

作者:Artech
出处:http://artech.cnblogs.com

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to the problem that Win11 system cannot install Chinese language pack Solution to the problem that Win11 system cannot install Chinese language pack Mar 09, 2024 am 09:48 AM

Solution to the problem that Win11 system cannot install Chinese language pack With the launch of Windows 11 system, many users began to upgrade their operating system to experience new functions and interfaces. However, some users found that they were unable to install the Chinese language pack after upgrading, which troubled their experience. In this article, we will discuss the reasons why Win11 system cannot install the Chinese language pack and provide some solutions to help users solve this problem. Cause Analysis First, let us analyze the inability of Win11 system to

Five tips to teach you how to solve the problem of Black Shark phone not turning on! Five tips to teach you how to solve the problem of Black Shark phone not turning on! Mar 24, 2024 pm 12:27 PM

As smartphone technology continues to develop, mobile phones play an increasingly important role in our daily lives. As a flagship phone focusing on gaming performance, the Black Shark phone is highly favored by players. However, sometimes we also face the situation that the Black Shark phone cannot be turned on. At this time, we need to take some measures to solve this problem. Next, let us share five tips to teach you how to solve the problem of Black Shark phone not turning on: Step 1: Check the battery power. First, make sure your Black Shark phone has enough power. It may be because the phone battery is exhausted

The driver cannot be loaded on this device. How to solve it? (Personally tested and valid) The driver cannot be loaded on this device. How to solve it? (Personally tested and valid) Mar 14, 2024 pm 09:00 PM

Everyone knows that if the computer cannot load the driver, the device may not work properly or interact with the computer correctly. So how do we solve the problem when a prompt box pops up on the computer that the driver cannot be loaded on this device? The editor below will teach you two ways to easily solve the problem. Unable to load the driver on this device Solution 1. Search for "Kernel Isolation" in the Start menu. 2. Turn off Memory Integrity, and it will prompt "Memory Integrity has been turned off. Your device may be vulnerable." Click behind to ignore it, and it will not affect the use. 3. The problem can be solved after restarting the machine.

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! Mar 15, 2024 pm 04:13 PM

1. How can you make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! 1. Activate basic rights and interests: original articles can earn profits by advertising, and videos must be original in horizontal screen mode to earn profits. 2. Activate the rights of 100 fans: if the number of fans reaches 100 fans or above, you can get profits from micro headlines, original Q&amp;A creation and Q&amp;A. 3. Insist on original works: Original works include articles, micro headlines, questions, etc., and are required to be more than 300 words. Please note that if illegally plagiarized works are published as original works, credit points will be deducted, and even any profits will be deducted. 4. Verticality: When writing articles in professional fields, you cannot write articles across fields at will. You will not get appropriate recommendations, you will not be able to achieve the professionalism and refinement of your work, and it will be difficult to attract fans and readers. 5. Activity: high activity,

Interpreting Oracle error 3114: causes and solutions Interpreting Oracle error 3114: causes and solutions Mar 08, 2024 pm 03:42 PM

Title: Analysis of Oracle Error 3114: Causes and Solutions When using Oracle database, you often encounter various error codes, among which error 3114 is a relatively common one. This error generally involves database link problems, which may cause exceptions when accessing the database. This article will interpret Oracle error 3114, discuss its causes, and give specific methods to solve the error and related code examples. 1. Definition of error 3114 Oracle error 3114 pass

How to solve the problem of low sound on Apple mobile phones How to solve the problem of low sound on Apple mobile phones Mar 08, 2024 pm 01:40 PM

The problem of low sound on Apple phones may be caused by many reasons. Users can try to solve the problem by adjusting the volume settings, checking the silent mode, clearing the speakers and earpieces, restarting the phone, checking the headphone jack, etc. How to solve the problem of low sound on Apple mobile phone 1. Adjust the volume setting First, make sure the volume setting of your mobile phone is correct. You can increase the volume by pressing the volume button (usually located on the side of the phone). In addition, you can also adjust the volume in "Sounds & Haptics" or "Sounds & Haptic Feedback" in settings. 2. Check the silent mode to make sure your phone is not in silent mode. You can look for the mute switch next to the volume buttons on the side. If the mute switch is on, the sound will be turned off. 3. Clean the speakers and earpieces. Sometimes the speakers and earpieces may be covered with dust.

Are you worried about WordPress backend garbled code? Try these solutions Are you worried about WordPress backend garbled code? Try these solutions Mar 05, 2024 pm 09:27 PM

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

See all articles