Created
April 10, 2012 15:30
-
-
Save jclement/2352144 to your computer and use it in GitHub Desktop.
Tinkering with Serializers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DataContract] | |
public class Contact | |
{ | |
public Contact() | |
{ | |
Children = new List<string>(); | |
Other = new Dictionary<string, int>(); | |
} | |
public Contact(int id, string name, string description) | |
{ | |
Id = id; | |
Name = name; | |
Description = description; | |
Children = new List<string>(); | |
Other = new Dictionary<string, int>(); | |
} | |
[DataMember] | |
public int? Id { get; set; } | |
[DataMember] | |
public string Name { get; set; } | |
[DataMember] | |
public string Description { get; set; } | |
[DataMember] | |
public List<string> Children { get; set; } | |
[DataMember] | |
public Dictionary<string, int> Other { get; set; } | |
[DataMember] | |
public Contact Spouse { get; set; } | |
} | |
public interface ISimpleSerializer<T> | |
{ | |
string serialize(T obj); | |
T unserialize(string data); | |
} | |
public abstract class SimpleSerializerBase<T>:ISimpleSerializer<T> | |
{ | |
protected abstract XmlObjectSerializer GetSerializer(); | |
public string serialize(T obj) | |
{ | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
GetSerializer().WriteObject(stream, obj); | |
stream.Seek(0, SeekOrigin.Begin); | |
using (TextReader textReader = new StreamReader(stream)) | |
{ | |
return textReader.ReadToEnd(); | |
} | |
} | |
} | |
public T unserialize(string data) | |
{ | |
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data))) | |
{ | |
return (T) GetSerializer().ReadObject(stream); | |
} | |
} | |
} | |
public class SimpleJsonSerializer<T>:SimpleSerializerBase<T> | |
{ | |
protected override XmlObjectSerializer GetSerializer() | |
{ | |
return new DataContractJsonSerializer(typeof (T)); | |
} | |
} | |
public class SimpleXmlSerializer<T>:SimpleSerializerBase<T> | |
{ | |
protected override XmlObjectSerializer GetSerializer() | |
{ | |
return new DataContractSerializer(typeof (T)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment