November 8, 2012

Just The Code: ToJson and ToXml Object Extension Methods (C#)

I have to be honest, I'm a pretty lazy coder. I'm so lazy, in fact, that I got annoyed by having to search through past projects to find JSON and XML serialization routines that I could copy for use in a current project. So, rather than go through the pain all over again, I decided to create two extension methods for the Object class: ToJson and ToXml. Both methods return strings in the same way that ToString does, but obviously one returns a JSON-formatted string while the other returns an XML-formatted string.

Here is the code so that you can be lazy like I am... note that you'll need to add a reference to System.Web.Extensions to your project in order to make use of the JavaScriptSerializer class.


Post a Comment