Skip to content

Instantly share code, notes, and snippets.

@jclement
Created April 10, 2012 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclement/2352144 to your computer and use it in GitHub Desktop.
Save jclement/2352144 to your computer and use it in GitHub Desktop.
Tinkering with Serializers
[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