Search This Site With Live Search

Welcome to MSDN Blogs Sign in | Join | Help

Use LINQ and .NET 3.5 to Convert RSS to JSON

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.

Published Tuesday, September 04, 2007 11:48 AM by kaevans

Comments

# MSDN Blog Postings &raquo; Use LINQ and .NET 3.5 to Convert RSS to JSON

# re: Use LINQ and .NET 3.5 to Convert RSS to JSON

Tuesday, September 04, 2007 4:38 PM by Hak Lynch

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!

# Creating a JSON Service with WebGet and WCF 3.5

Tuesday, September 04, 2007 7:31 PM by Kirk Allen Evans' Blog

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

# Creating a JSON Service with WebGet and WCF 3.5

Tuesday, September 04, 2007 7:43 PM by Noticias externas

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

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

Tuesday, October 02, 2007 1:36 AM by ScottGu's Blog

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

Tuesday, October 02, 2007 2:01 AM by BusinessRx Reading List

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

Tuesday, October 02, 2007 2:23 AM by Elan's Aggregated Blogs

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

# Some .NET 3.5 features application

Tuesday, October 02, 2007 11:09 AM by Technoeuphoria!

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

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

Wednesday, October 03, 2007 11:00 PM by ASPInsiders

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

Sunday, October 07, 2007 10:48 PM by Kelvin Zhang

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

# 技巧/诀窍:用 .NET 3.5 创建 ToJSON() 扩展方法 (木野狐译)

Tuesday, October 09, 2007 10:53 PM by Joycode@Ab110.com

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

# http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx

Friday, October 19, 2007 4:43 AM by TrackBack

# http://blogs.msdn.com/shahpiyush/archive/2007/04/12/2103116.aspx

Friday, October 19, 2007 4:43 AM by TrackBack

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

Saturday, October 20, 2007 8:35 PM by Programming

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

# Calling Web Services via AJAX - Part 2

Thursday, April 10, 2008 10:32 AM by Kirk Allen Evans's Blog

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

New Comments to this post are disabled
 
Page view tracker