次の方法で共有


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 = "https://purl.org/rss/1.0/modules/slash/";

        XDocument rssFeed = XDocument.Load("https://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.

Comments

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

  • Anonymous
    September 04, 2007
    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!

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

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

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

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

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

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

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

  • Anonymous
    October 07, 2007
    Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5

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

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

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

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

  • Anonymous
    December 16, 2008
    I was re-reading this post from Kirk Allen Evan&#39;s Blog when I decided to fool around with making

  • Anonymous
    December 18, 2008
    .NET3.5还包含一个新的newSystem.Runtime.Serialization.DataContractJsonSerializerclass类,你也可以用它来做JSON(J...

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

  • Anonymous
    January 05, 2009
    I was re-reading this post from Kirk Allen Evan&#39;s Blog when I decided to fool around with making

  • Anonymous
    January 06, 2009
    I was re-reading this post from Kirk Allen Evan&#39;s Blog when I decided to fool around with making