Click here to Skip to main content
15,884,099 members
Articles / Web Development / HTML

Implementing a JSON Feed with ASP.NET

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Jun 2012CPOL1 min read 13.5K   4   2
A JSON feed implementation to a service that provides quotes for precious metals

Introduction

JSON represents data structures using a JavaScript object notation which is human readable. It provides some advantages over XML because it is easier to obtain data from multilevel (nested) structures. Below is an example of a JSON feed implementation to a service that provides quotes for precious metals at http://drayah.no.de/metals/latest. The objective is to get the feed from the site in order to obtain the price of Gold.

Step 1. Create a Class for JSON Feed

You may want to use the JsonCSharp tool that helps you create a class based on the output from the feed. Check it out at http://json2csharp.com/.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace JSONFeed
{
    public class Gold
    {
        public double quote { get; set; }
        public double quoteKg { get; set; }
    }

    public class Silver
    {
        public double quote { get; set; }
        public double quoteKg { get; set; }
    }

    public class Platinum
    {
        public double quote { get; set; }
        public double quoteKg { get; set; }
    }

    public class Palladium
    {
        public double quote { get; set; }
        public double quoteKg { get; set; }
    }

    public class Metals
    {
        public Gold gold { get; set; }
        public Silver silver { get; set; }
        public Platinum platinum { get; set; }
        public Palladium palladium { get; set; }
    }
}

Step 2. Creating a Method to Invoke the Feed

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web.Configuration;
namespace JSONFeed
{
public class GetFeed
{
    public double GoldPrice()
    {
        try
        {
            //Get Precious Metals Pricess from Drayah feed 
            //http://drayah.no.de/metals/latest
            string url = "http://drayah.no.de/metals/latest";
            WebRequest request = WebRequest.Create(url);
            WebResponse ws = request.GetResponse();
            //Used http://json2csharp.com/ to auto-generate C# Class 
            //for the Json feed. 
            //DataContractJsonSerializer will Serialize based on another 
            //class named Metals
            DataContractJsonSerializer jsonSerializer = 
                         new DataContractJsonSerializer(typeof(Metals));
            Metals _metals = 
               (Metals)jsonSerializer.ReadObject(ws.GetResponseStream());
            if (_metals.gold.quote > 0)
                return _metals.gold.quote;
            else
                return 0;
        }
         //Add your exception code here.
        catch (Exception ex)
        {
            return 0;
        }
    }
}
}

Step 3. Test Class to Run and Test the Feed

If you believe in using Visual Studio Automated Testing Classes, use the below:

C#
using JSONFeed;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web; namespace JSONFeed.Test
{        
    [TestClass()]
    public class GetFeedTest
    {
        private TestContext testContextInstance;
        /// 
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///

        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #endregion
        [TestMethod()]
        public void GoldPriceTest()
        {
            GetFeed target = new GetFeed(); 
            double actual;

            actual = target.GoldPrice();
            Assert.AreNotEqual(0, actual);
        }
    }
}

The GoldPrice() method invokes the jsonSerializer which will try to match the output of the feed with the appropriate class which in this case is the class named Metals. The data will be filled into the corresponding subclass. If the data contains multiple rows of information, it needs to be defined as a list so the serializer knows that multiple rows are affected.

Below is a screenshot of the output after it's been serialized.

Image 1

Hope this helps. Happy coding!

This article was originally posted at http://feeds.feedburner.com/blogspot/NyVKAz

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFeed down? Pin
markwoodlief29-Nov-12 3:37
markwoodlief29-Nov-12 3:37 
http://drayah.no.de/metals/latest[^]

is no longer active... nice article but since the feed no longer works you can't really step through the code.. Frown | :(
AnswerRe: Feed down? Pin
gmtzgtz29-Nov-12 15:33
gmtzgtz29-Nov-12 15:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.