Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Implementing a JSON Feed with ASP.NET

0.00/5 (No votes)
7 Jun 2012 1  
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/.

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

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:

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.

Hope this helps. Happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here