This article mainly describes the serialization and deserialization of XML and objects. Some simple serialization and deserialization methods will be attached for your use.
Suppose we have two classes in a Web project:
Copy codeThe Code is as follows:
Public class Member
{
Public string Num {get; set ;}
Public string Name {get; set ;}
}
Public class Team
{
Public string Name;
Public List <Member> Members {get; set ;}
}
Suppose we need to POST an instance of the Team class to a URL,
Of course, you can use Form to hide the field commit.
What if the Team contains 30 pieces of data?
To distinguish each Member, we need to add a suffix to the parameter name. This requires a large string of hidden domains:
Copy codeThe Code is as follows:
<! -- Use Razor to demonstrate -->
@ Model Team
<Form id = "submitForm" action = "http://www.johnconnor.com/team" method = "post">
<Input type = "hidden" name = "TeamName" value = "@ Model. Name"/>
<Input type = "hidden" name = "MemberNum1" value = "@ Model. Members [0]. Num"/>
<Input type = "hidden" name = "MemberName1" value = "@ Model. Members [0]. Name"/>
...
<! -- 28 X input tags are omitted -->
<Input type = "hidden" name = "MemberNum30" value = "@ Model. Members [29]. Num"/>
<Input type = "hidden" name = "MemberName30" value = "@ Model. Members [29]. Name"/>
</Form>
<Script type = "text/javascript">
Document. getElementById ("submitForm"). submit ();
</Script>
Do you dare to imagine if the Team is more complex and nested?
Er, even if you are willing to upload data like this, it is a headache for the other party to see a batch of parameter names.
We all know that objects cannot be transmitted directly on the network, but there are still ways to remedy them.
XML (Extensible Markup Language)The extensible markup language is designed to store data. Any object can be described in XML. Take the Team class as an example:
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Team xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<Name> Development </Name>
<Members>
<Member>
<Num> 001 </Num>
<Name> Marry </Name>
</Member>
<Member>
<Num> 002 </Num>
<Name> John </Name>
</Member>
</Members>
</Team>
Such an XML document represents an instance of the Team.
The intelligent viewer should have thought that XML can be transmitted in the network as a carrier of object information, because it is in the form of text.
How can we convert XML documents and objects?
The XmlSerializer class does this job.
Namespace: System. Xml. Serialization
Assembly: System. Xml (in system. xml. dll)
The following shows an EncodeHelper class that provides serialization and deserialization methods.
The Deserialize method converts an XML string to an object of the specified type;
The Serialize method converts an object to an XML string.
Copy codeThe Code is as follows:
/// <Summary>
/// Provide xml document serialization and deserialization
/// </Summary>
Public sealed class EncodeHelper
{
/// <Summary>
/// Deserialization the XML string is of the specified type
/// </Summary>
Public static object Deserialize (string Xml, Type ThisType)
{
XmlSerializer xmlSerializer = new XmlSerializer (ThisType );
Object result;
Try
{
Using (StringReader stringReader = new StringReader (Xml ))
{
Result = xmlSerializer. Deserialize (stringReader );
}
}
Catch (Exception innerException)
{
Bool flag = false;
If (Xml! = Null)
{
If (Xml. StartsWith (Encoding. UTF8.GetString (Encoding. UTF8.GetPreamble ())))
{
Flag = true;
}
}
Throw new ApplicationException (string. Format ("Couldn't parse XML: '{0}'; Contains BOM: {1}; Type: {2 }.",
Xml, flag, ThisType. FullName), innerException );
}
Return result;
}
/// <Summary>
/// Serialize the object as an XML string
/// </Summary>
Public static string Serialize (object ObjectToSerialize)
{
String result = null;
Try
{
XmlSerializer xmlSerializer = new XmlSerializer (ObjectToSerialize. GetType ());
Using (MemoryStream memoryStream = new MemoryStream ())
{
XmlTextWriter xmlTextWriter = new XmlTextWriter (memoryStream, new UTF8Encoding (false ));
XmlTextWriter. Formatting = Formatting. Indented;
XmlSerializer. Serialize (xmlTextWriter, ObjectToSerialize );
XmlTextWriter. Flush ();
XmlTextWriter. Close ();
UTF8Encoding uTF8Encoding = new UTF8Encoding (false, true );
Result = uTF8Encoding. GetString (memoryStream. ToArray ());
}
}
Catch (Exception innerException)
{
Throw new ApplicationException ("Couldn't Serialize Object:" + ObjectToSerialize. GetType (). Name, innerException );
}
Return result;
}
}
To use this class, add the following reference:
Using System;
Using System. Text;
Using System. IO;
Using System. Xml;
Using System. Xml. Serialization;
The following uses a console program to demonstrate how this class works. Here is the Main function of the program.
Copy codeThe Code is as follows:
Static void Main (string [] args)
{
List <Member> Members = new List <Member> ();
Member member1 = new Member {Name = "Marry", Num = "001 "};
Member member2 = new Member {Name = "John", Num = "002 "};
Members. Add (member1 );
Members. Add (member2 );
Team team = new Team {Name = "Development", Members = Members };
Var xml = EncodeHelper. Serialize (team); // serialization
Console. Write (xml); // print the serialized XML string
Console. ReadLine ();
Team newTeam = EncodeHelper. Deserialize (xml, typeof (Team) as Team; // explicit type conversion is required for deserialization.
Console. WriteLine ("Team Name:" + newTeam. Name); // display the deserialized newTeam object
Foreach (var member in newTeam. Members)
{
Console. WriteLine ("Member Num:" + member. Num );
Console. WriteLine ("Member Name:" + member. Name );
}
Console. ReadLine ();
}
After executing the Console. Write (xml) line of code, you can see the printed XML document.
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Team xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<Name> Development </Name>
<Members>
<Member>
<Num> 001 </Num>
<Name> Marry </Name>
</Member>
<Member>
<Num> 002 </Num>
<Name> John </Name>
</Member>
</Members>
</Team>
The example at the beginning of the article is exactly the same.
This is the final result of the deserialization of the newTeam object.
Team Name: Development
Member Num: 001
Member Name: Marry
Member Num: 002
Member Name: John
Back to the Web communication example we started,
Using XML serialization and deserialization for object transmission, we only need to serialize the object to be passed into an XML string and use a hidden field for form submission!
The receiver deserializes the received XML string into a preset object. The premise is that both parties must agree that the serialization process is consistent with the deserialization process, and the object is the same.
Finally, let's take a look at how to use some features to control the serialization and deserialization operations. Let's change the starting class:
Copy codeThe Code is as follows:
Public class Member
{
[XmlElement ("Member_Num")]
Public string Num {get; set ;}
Public string Name {get; set ;}
}
[XmlRoot ("Our_Team")]
Public class Team
{
[XmlIgnore] public string Name;
Public List <Member> Members {get; set ;}
}
Then we run the console program again, and the serialization result is as follows:
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Our_Team xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<Members>
<Member>
<Member_Num> 001 </Member_Num>
<Name> Marry </Name>
</Member>
<Member>
<Member_Num> 002 </Member_Num>
<Name> John </Name>
</Member>
</Members>
</Our_Team>
The root node Team is changed to Our_Team, and the child node Num of Member is changed to Member_Num, and the Name subnode of the Team is ignored.
Visible feature XmlRoot can control the display and operation process of the root node, while XmlElement is for the child node. If some Members are marked as XmlIgnore, they are ignored during serialization and deserialization.
The specific content of these features can be viewed on MSDN.
With this knowledge, it is difficult to pass object data in the network. Pai_^