12 April 2007

Convert Rss to JSON - Serialize to JSON by using XmlSerialization and JavaScriptSerializer

JSON (Javascript Object Notation) – is a light weight data interchange format.  It essentially is composed of key-value pairs.  For Example –

 XML

<rss version="2.0">

  <channel>

    <item>

      <link>http://test.com</link>

      <title>Page Title</title>

    </item>

  </channel>

</rss>

JSON  -

{
   "Version":"2.0",
   "Channel": {
         "Items": [{
               "Link":"http://test.com",
               "Title":"Page Title"
          }]
       }
}

The beauty of JSON is it integrates easily with Javascript. Just use eval() function of JavaScript to parse. So to initialize the above JSON this should do the trick –

var rss = eval(‘({ "Version":"2.0", "Channel": { "Items": [{Link":"http://test.com",Title":"Page Title" }]}}’);

Javascript does provide some level of Object orientation. So you could access the properties from the above object like –

var itemtitle = rss.Channel.Items[0].Title;
var rssVersion = rss.Version;

RSS (Really Simple Syndication) – is used to syndicate your content. Unless you were hibernating for the past 5 years, I’m sure you know what Rss is. :)


So let’s get to the meat of this article. How to Convert an Rss Feed to JSON?

First I will use XmlSerialization to Serialize/Deserialize Rss. The System.Xml.Serialization namespace is  used for this purpose. You will need to decorate all your properties with XmlSerialization attributes. E.g. –

[XmlElement("description")]

public string Description

{

get

      {

            return _description;

      }

 

      set

      {

            _description = value;

      }

}

In this example (code provided below) I have created classes closely matching Rss specification (http://blogs.law.harvard.edu/tech/rss)

To Serialize you can use the Serialize() method of XmlSerializer class

private string Serialize()

{

string xml = string.Empty;

 

      using (StringWriter output = new StringWriter(new StringBuilder(), System.Globalization.CultureInfo.InvariantCulture))

      {

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(RssDocument));

            xmlSerializer.Serialize(output, this);

            xml = output.ToString();

      }

 

      return xml;

}

To Deserialize you can use the Deserialize ) method of XmlSerializer class

private static T DeserializeFromXmlUsingStringReader<T>(string xml)

{

if (string.IsNullOrEmpty(xml))

      {

            throw new ArgumentException("xml");

      }

 

      XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

      using (StringReader strngReader = new StringReader(xml))

      {

            return (T)xmlSerializer.Deserialize(strngReader);

      }

}

This should create a Strongly typed representation of Rss.

To convert this Strongly typed Rss classes to Json format is actually very easy.  ASP.Net AJAX provides JavaScriptSerializer class in System.Web.Script.Serialization.JavascriptSerializer.


Of particular importance to this example in this table is Serialize(object) method.

public string ToJson()

{

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

      return js.Serialize(this); //this is an instance of the strongly typed Rss Class

}

What’s cool is this technique can be used on any objects which uses XmlSerialization.

I have code example in the attachment below with example on how to Convert Rss to Json by pointing to a Url or loading from Xml string.

Note : To run the example you need to have ASP.Net 2.0 and Ajax Extensions. You can download it from here

 

Attachment(s):RssToJson.zip
 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Nick Parsons said:

Nice post! Great idea of using XmlSerialization and JavascriptSerializer. I'll try it out.

01 May 07 at 3:09 AM
# kaevans said:

Very cool!  Note that you can also do this out of the box using .NET 3.5.  

http://blogs.msdn.com/kaevans/archive/2007/09/04/use-linq-and-net-3-5-to-convert-rss-to-json.aspx

04 September 07 at 1:51 PM
# Hank Lynch said:

So I found this article after....after downloading JSONSharp and messing about with it for an afternoon.

Very nice.

25 October 07 at 10:45 AM
# Robert Robbins said:

In attempting to use the Microsoft AJAX Library 1.0 in a MSHelp2 collection (to be viewed in the Microsoft

16 December 07 at 4:59 PM
# Blogs and RSS » Piyush Shah’s Blog : Convert Rss to JSON - Serialize to JSON by using … said:

PingBack from http://blogrssblog.info/piyush-shahs-blog-convert-rss-to-json-serialize-to-json-by-using/

16 March 08 at 12:52 AM
# Piyush Shah s Blog Convert Rss to JSON Serialize to JSON by using | Green Tea Fat Burner said:

PingBack from http://greenteafatburner.info/story.php?id=1772

09 June 09 at 3:01 PM
# Piyush Shah s Blog Convert Rss to JSON Serialize to JSON by using | Outdoor Decor said:

PingBack from http://outdoordecoration.info/story.php?id=1479

13 June 09 at 6:10 PM
# Piyush Shah s Blog Convert Rss to JSON Serialize to JSON by using | debt settlement program said:

PingBack from http://edebtsettlementprogram.info/story.php?id=22738

15 June 09 at 1:14 PM

Leave a Comment

Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker