Object serialization in .Net is pretty easy, once you have the right code. It took me a few minutes to figure out the right code so I thought I’d post it here. The code below is a working C# console app.
Code Snippet
- using System;
- using System.IO;
- using System.Xml.Serialization;
- namespace TestApp
- {
- public class Program
- {
- static string serializedObject;
- static void Main(string[] args)
- {
- Serialize();
- Deserialize();
- }
- static void Serialize()
- {
- Person p = new Person() { Age = 20, Name = "Bob" };
- XmlSerializer serializer = new XmlSerializer(p.GetType());
- using (StringWriter sw = new StringWriter())
- {
- serializer.Serialize(sw, p);
- serializedObject = sw.GetStringBuilder().ToString();
- }
- }
- static void Deserialize()
- {
- XmlSerializer serializer = new XmlSerializer(typeof(Person));
- Person p = (Person)serializer.Deserialize(new StringReader(serializedObject));
- Console.WriteLine("Name:" + p.Name + " Age:" + p.Age);
- Console.ReadLine();
- }
- public class Person
- {
- public int Age { get; set; }
- public string Name { get; set; }
- }
- }
- }
No comments:
Post a Comment