Deserializing POC Objects From Strings Using RestSharp
Join the DZone community and get the full member experience.
Join For FreeRestSharp 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.
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 });
Strings
Object (computer science)
Opinions expressed by DZone contributors are their own.
Comments