Deserializing POC Objects From Strings Using RestSharp
RestSharp is a wonderful little library for communicating with REST services. There is one thing I like in particular – their forgiving deserialization classes. They are awesome, but they cannot deserialize plain strings. If you take a closer look at the Deserialize methods, you will notice that they accept an object of the class that implements IRestResponse. If you inspect the source code (it is open source over at github), you will see that only Content property is used.
Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)So, let’s implement our FakeResponse class that will wrap our string:
public class FakeResponse : IRestResponse
{
public string Content { get; set; }
// default implementation is OK
}
You can now deserialize it with the following snippet (xml holds the XML text read from some source other than web response):
var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
var rss = xmlDeserializer.Deserialize<Data.Rss>(new FakeResponse() { Content = xml });
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Tags:




