Kirk Evans Blog

.NET From a Markup Perspective

Use LINQ and .NET 3.5 to Convert RSS to JSON

Use LINQ and .NET 3.5 to Convert RSS to JSON

  • Comments 21

Scott Guthrie posted a great example of how to create a feed reader using LINQ to XML.  Today, I see Tim Heuer's post on the JavaScriptSerializer type in .NET 3.5.  So, I thought I would mash them up and show how to use LINQ to implement Tim's idea of converting RSS to JSON.  Unfortunately, the JavaScriptSerializer is marked as obsolete with a note to use the DataContractJsonSerializer instead.  Here is what a generic HTTP Handler would look like that mashes up these techniques using .NET 3.5.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Linq;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Collections.Generic;


public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        XNamespace slashNamespace = "http://purl.org/rss/1.0/modules/slash/";

        XDocument rssFeed = XDocument.Load("http://blogs.msdn.com/kaevans/rss.aspx");
        var posts = from item in rssFeed.Descendants("item")
                    select new
                    {
                        Title = item.Element("title").Value,
                        Published = DateTime.Parse(item.Element("pubDate").Value),
                        Url = item.Element("link").Value,
                        NumComments = int.Parse(item.Element(slashNamespace + "comments").Value)
                    };

        var newPosts = from item in posts
                       where (DateTime.Now - item.Published).Days < 7
                       select item;

        List<FeedItem> itemsList = new List<FeedItem>();
        foreach (var item in newPosts)
        {
            itemsList.Add(new FeedItem { Title = item.Title, Published = item.Published, Url = item.Url, NumComments = item.NumComments });
        }

        DataContractJsonSerializer ser = new DataContractJsonSerializer(itemsList.GetType());        
        ser.WriteObject(context.Response.OutputStream, itemsList);        
         
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


[DataContract]
public class FeedItem
{
    [DataMember] public string Title { get; set; }
    [DataMember] public DateTime Published { get; set; }
    [DataMember] public string Url { get; set; }
    [DataMember] public int NumComments { get; set; }
}

Look at how simple that is!  Using LINQ, we are able to get just the posts that were published within the past 7 days, and we serialize the result to JSON.  The results are shown below.

[{"NumComments":0,"Published":"\/Date(1188917760000-0500)\/",
    "Title":"Using WCF, JSON, LINQ, and AJAX: Passing Complex Types to WCF Services with JSON Encoding",
    "Url":"http:\/\/blogs.msdn.com\/kaevans\/archive\/2007\/09\/04\/using-wcf-json-linq-and-ajax-passing-complex-types-to-wcf-services-with-json-encoding.aspx"},
{"NumComments":4,"Published":"\/Date(1188836640000-0500)\/",
    "Title":"WCF and LINQ",
    "Url":"http:\/\/blogs.msdn.com\/kaevans\/archive\/2007\/09\/03\/wcf-and-linq.aspx"},
{"NumComments":1,"Published":"\/Date(1188652680000-0500)\/",
    "Title":"Are you ready for some football?!?!",
    "Url":"http:\/\/blogs.msdn.com\/kaevans\/archive\/2007\/09\/01\/are-you-ready-for-some-football.aspx"}] 

So very cool.  Look at how terse yet readable that code is!  Contrast that to something like this from only a couple of years ago... Getting XML From Somewhere Else, which doesn't even cover filtering the XML and converting to JSON... which I probably would have transformed using some bizarre XSLT geekery.  This is cleaner and easier to understand.

  • PingBack from http://msdnrss.thecoderblogs.com/2007/09/04/use-linq-and-net-35-to-convert-rss-to-json/

  • Thanks for the code!  That is some seriously clean code, and you're right, a couple of years ago, this would have been a mess.  Can't wait to get the go ahead from my boss to start using this stuff!

  • I couldn't let it go. Tim's post had me intrigued about how to convert RSS to JSON using some of the

  • I couldn&#39;t let it go. Tim&#39;s post had me intrigued about how to convert RSS to JSON using some

  • Earlier this year I blogged about a new language extensibility feature of C# and VB called "Extension

  • Earlier this year I blogged about a new language extensibility feature of C# and VB called "Extension

  • Earlier this year I blogged about a new language extensibility feature of C# and VB called &quot;Extension

  • It&#39;s been a while since I got time to read up on some blog posts and I stumbled on some interesting

  • Earlier this year I blogged about a new language extensibility feature of C# and VB called "Extension

  • Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5

  • 【原文地址】 Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5 【原文发表日期】 Monday, October 01, 2007

  • Earlier this year I blogged about&amp;;a new language extensibility&amp;;feature of C# and VB called

  • Looks like this is an interesting topic to a lot of people since part 1 of this series made it to the

Page 1 of 2 (21 items) 12
Leave a Comment
  • Please add 3 and 3 and type the answer here:
  • Post
Translate This Page
Search
Archive
Archives