[RESOLVED]Parsing REST Services JSON Responses (MSDN tutorial)

I am looking at a
MSDN tutorial
that explains how to parse REST services JSON responses.

The tutorial makes a request to the Bing Maps REST service, then parses the response.

My problem is that I don’t get what I need to do to use sample code.

My approach has been to create a new Class C# file with the name Distance:

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// Summary description for sample
/// </summary>
public class Distance
{
    public Distance()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}

Changed the directives to the ones from the sample, then I copied the sample code where it says "Add constructor logic here" (without the //).

Then I got rid of namespace RESTServicesJSONParser example and the two brackets {}.

Now I end up with VS squigly lines on Response "the type or namespace name "Response could not be found, are you using directive of an assembly reference, and the same for Location.

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Collections.Generic;


/// <summary>
/// Summary description for Distance
/// </summary>

public class Distance
{


    class Program
    {
        static string BingMapsKey = "AsTUY"; 
        static void Main(string[] args)
        {           
            try
            {
                string locationsRequest = CreateRequest("New%20York"); 
                Response locationsResponse = MakeRequest(locationsRequest);
                ProcessResponse(locationsResponse);
  }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
            }

        }

        //Create the request URL
        public static string CreateRequest(string queryString)
        {
            string UrlRequest = "http://dev.virtualearth.net/REST/v1/Locations/" +
                                           queryString +
                                           "?key=" + BingMapsKey;
            return (UrlRequest);
        }

        public static Response MakeRequest(string requestUrl)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
                    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                    Response jsonResponse
                    = objResponse as Response;
                    return jsonResponse;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }

        }

        static public void ProcessResponse(Response locationsResponse)
        {

            int locNum = locationsResponse.ResourceSets[0].Resources.Length;

            //Get formatted addresses: Option 1
            //Get all locations in the response and then extract the formatted address for each location
            Console.WriteLine("Show all formatted addresses");
            for (int i = 0; i < locNum; i++)
            {
                Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
                Console.WriteLine(location.Address.FormattedAddress);
            }
            Console.WriteLine();
            
            //Get the Geocode Points for each Location
            for (int i = 0; i < locNum; i++)
            {
               Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
               Console.WriteLine("Geocode Points for "+location.Address.FormattedAddress);               
               int geocodePointNum = location.GeocodePoints.Length;
               for (int j = 0; j < geocodePointNum; j++)
               {
                   Console.WriteLine("    Point: "+location.GeocodePoints[j].Coordinates[0].ToString()+","+
                                                location.GeocodePoints[j].Coordinates[1].ToString());
                   double test = location.GeocodePoints[j].Coordinates[1];
                   Console.Write("    Usage: ");              
                   for (int k = 0; k < location.GeocodePoints[j].UsageTypes.Length; k++)
                   {                                                     
                      Console.Write(location.GeocodePoints[j].UsageTypes[k].ToString()+" ");
                   }
                   Console.WriteLine("nn");
               }
            }
            Console.WriteLine();


            //Get all locations that have a MatchCode=Good and Confidence=High
            Console.WriteLine("Locations that have a Confidence=High");
            for (int i = 0; i < locNum; i++)
            {
                Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
                if (location.Confidence == "High")
                    Console.WriteLine(location.Address.FormattedAddress);
            }
                        Console.WriteLine();

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();


        }
    }
       
        


    }

Did you do the "Create the data contract" part?  That is where the Response class is defined.  If you have done it, make sure you add the right "using" to the top of your page to match the class’ namespace (or from visual studio, right-click the Response
word and use the Resolve menu to do this for you.  If you can’t get that working, just add the Response class in the same file as your Program class.

No, I did not.

Same question though…

This is the sample code for Response, what does this tell me? Are these C class files? What modifications do I need to make to the standard template shown above?

public static Response MakeRequest(string requestUrl)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception(String.Format(
                "Server error (HTTP {0}: {1}).",
                response.StatusCode,
                response.StatusDescription));
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
            object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
            Response jsonResponse
            = objResponse as Response;
            return jsonResponse;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}

@AidyF…

Is the code for creating the data contract also a class C file? What name should that file have?

TIA Robert

Just add a class file (a cs) file and call it Response.cs and put that code in it.  The name isn’t relevant, you can call it anything, but convention says you call the file the same name as the class inside it.

Ok, that did it (with some youtube videos).

Got my test project running.

Feed it two addressed and it returns the distance and travel time.

Leave a Reply