Click here to Skip to main content
Click here to Skip to main content

Implementing a JSON Feed with ASP.NET

, 7 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

gmtzgtz

United States United States
No Biography provided

Comments and Discussions

 
QuestionFeed down? Pinmembermarkwoodlief29-Nov-12 3:37 
AnswerRe: Feed down? Pinmembergmtzgtz29-Nov-12 15:33 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 7 Jun 2012
Article Copyright 2012 by gmtzgtz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid