Skip to content

Instantly share code, notes, and snippets.

@mganss
Last active December 16, 2015 21:39
Show Gist options
  • Save mganss/5501597 to your computer and use it in GitHub Desktop.
Save mganss/5501597 to your computer and use it in GitHub Desktop.
A RestSharp XML deserializer that can deserialize derived classes.

Assume you have these classes:

public class Base
{
}

public class Derived : Base
{
}

The RestSharp.Deserializers.DotNetXmlDeserializer (which uses System.Xml.Serialization.XmlSerializer) fails when trying to deserialize the following to Base:

<?xml version="1.0" encoding="utf-8"?>
<Derived />

This deserializer checks the root element's name to determine the type to deserialize to using reflection.

using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace RestSharpXmlDeserializer
{
/// <summary>
/// This deserializer checks the root element's name to determine the type to deserialize to using reflection.
/// </summary>
public class BaseXmlDeserializer : IDeserializer
{
public string DateFormat { get; set; }
public string Namespace { get; set; }
public string RootElement { get; set; }
public T Deserialize<T>(IRestResponse response)
{
if (string.IsNullOrEmpty(response.Content))
{
return default(T);
}
var root = XElement.Parse(response.Content).Name.LocalName;
var type = typeof(T);
if (!string.Equals(type.Name, root, StringComparison.OrdinalIgnoreCase))
{
type = Assembly.GetAssembly(type).GetTypes()
.First(t => t != type && type.IsAssignableFrom(t) && string.Equals(t.Name, root, StringComparison.OrdinalIgnoreCase));
}
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
{
var serializer = new System.Xml.Serialization.XmlSerializer(type);
return (T)serializer.Deserialize(stream);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment