This tutorial shows you how to parse a Bing Maps REST Services JSON request using C# and includes basic sample code. The process is described in three steps:
- Create the basic program
- Create the data contract
- Create the Request
- Make the request
- Process the response
Create the basic program
Start Visual Studio and create a C# .NET console application named RESTServicesJSONParserExample. Replace the default template with the following sample code, and insert your Bing Maps Key in place of the placeholder insertYourBingMapsKey. If you do not have a Bing Maps Key, see Getting a Bing Maps Key.
using System; using System.Net; using System.Runtime.Serialization.Json; namespace RESTServicesJSONParserExample { class Program { static string BingMapsKey = "InsertYourBingMapsKeyHere"; 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 REST Services request
Insert the following method into your program. This method creates a simple location query for “New York”. This type of Bing Maps REST Services Locations API request is described in Find a Location by Query.
public static string CreateRequest(string queryString) { string UrlRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + queryString + "?output=xml" + " &key=" + BingMapsKey; return (UrlRequest); }
Create the REST Services request
Insert the following method into your program. This method creates a simple location query for “New York”. This type of Bing Maps REST Services Locations API request is described in Find a Location by Query.
public static string CreateRequest(string queryString) { string UrlRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + queryString + "?output=xml" + " &key=" + BingMapsKey; return (UrlRequest); }
Make the request
Insert the following code to make REST Services HTTP requests and return the response.
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; } }
Create the data contract
Add a new C# class to your project and replace the template content with the data contract classes below. These data contracts describe location data that is returned in the JSON response when you make a Locations API geocode request. You can compare the class structure with the example response at the end of this article. You can also create similar contracts for the JSON responses to other REST Services requests.
using System.Runtime.Serialization; using System.Runtime.Serialization.Json; namespace RESTServicesJSONParserExample { [DataContract] public class Response { [DataMember(Name = "copyright")] public string Copyright { get; set; } [DataMember(Name = "brandLogoUri")] public string BrandLogoUri { get; set; } [DataMember(Name = "statusCode")] public int StatusCode { get; set; } [DataMember(Name = "statusDescription")] public string StatusDescription { get; set; } [DataMember(Name = "authenticationResultCode")] public string AuthenticationResultCode { get; set; } [DataMember(Name = "errorDetails")] public string[] errorDetails { get; set; } [DataMember(Name = "traceId")] public string TraceId { get; set; } [DataMember(Name = "resourceSets")] public ResourceSet[] ResourceSets { get; set; } } [DataContract] public class ResourceSet { [DataMember(Name = "estimatedTotal")] public long EstimatedTotal { get; set; } [DataMember(Name = "resources")] public Location[] Resources { get; set; } } [DataContract] public class Point { /// <summary> /// Latitude,Longitude /// </summary> [DataMember(Name = "coordinates")] public double[] Coordinates { get; set; } } [DataContract] public class BoundingBox { [DataMember(Name = "southLatitude")] public double SouthLatitude { get; set; } [DataMember(Name = "westLongitude")] public double WestLongitude { get; set; } [DataMember(Name = "northLatitude")] public double NorthLatitude { get; set; } [DataMember(Name = "eastLongitude")] public double EastLongitude { get; set; } } [DataContract] public class GeocodePoint: Point { [DataMember(Name = "calculationMethod")] public string CalculationMethod { get; set; } [DataMember(Name = "usageTypes")] public string[] UsageTypes { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1")] public class Location { [DataMember(Name = "boundingBox")] public BoundingBox BoundingBox { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "point")] public Point Point { get; set; } [DataMember(Name = "entityType")] public string EntityType { get; set; } [DataMember(Name = "address")] public Address Address { get; set; } [DataMember(Name = "confidence")] public string Confidence { get; set; } [DataMember(Name = "geocodePoints")] public GeocodePoint[] GeocodePoints { get; set; } [DataMember(Name = "matchCodes")] public string[] MatchCodes { get; set; } } [DataContract] public class Address { [DataMember(Name = "addressLine")] public string AddressLine { get; set; } [DataMember(Name = "adminDistrict")] public string AdminDistrict { get; set; } [DataMember(Name = "adminDistrict2")] public string AdminDistrict2 { get; set; } [DataMember(Name = "countryRegion")] public string CountryRegion { get; set; } [DataMember(Name = "formattedAddress")] public string FormattedAddress { get; set; } [DataMember(Name = "locality")] public string Locality { get; set; } [DataMember(Name = "postalCode")] public string PostalCode { get; set; } } }
Process the request
Insert the following code in the original file. This code extracts data from the response using the data contract classes.
static public void ProcessResponse(Response locationsResponse) { int locNum = locationsResponse.ResourceSets[0].Resources.Length; //Get formatted addresses //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("\n\n"); } } 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(); }
Request and Response
This sample code below creates the following request and extracts information from the response.
http://dev.virtualearth.net/REST/v1/Locations/New%20York?output=xml&key=insertYourBingMapsKey
{ "authenticationResultCode":"ValidCredentials", "brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png", "copyright":"Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.", "resourceSets":[ { "estimatedTotal":3, "resources":[ { "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "bbox":[ 40.36376953125, -74.745925903320312, 41.056510925292969, -73.267219543457031 ], "name":"New York, NY", "point":{ "type":"Point", "coordinates":[ 40.714550018310547, -74.007118225097656 ] }, "address":{ "adminDistrict":"NY", "countryRegion":"United States", "formattedAddress":"New York, NY", "locality":"New York" }, "confidence":"High", "entityType":"PopulatedPlace", "geocodePoints":[ { "type":"Point", "coordinates":[ 40.714550018310547, -74.007118225097656 ], "calculationMethod":"Rooftop", "usageTypes":[ "Display" ] } ], "matchCodes":[ "Good" ] }, { "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "bbox":[ 53.049841262515258, -0.204358685176537, 53.107782028500367, -0.075841319401099713 ], "name":"New York, Lincs, United Kingdom", "point":{ "type":"Point", "coordinates":[ 53.078811645507812, -0.14010000228881836 ] }, "address":{ "adminDistrict":"England", "adminDistrict2":"Lincs", "countryRegion":"United Kingdom", "formattedAddress":"New York, Lincs, United Kingdom", "locality":"New York" }, "confidence":"High", "entityType":"PopulatedPlace", "geocodePoints":[ { "type":"Point", "coordinates":[ 53.078811645507812, -0.14010000228881836 ], "calculationMethod":"Rooftop", "usageTypes":[ "Display" ] } ], "matchCodes":[ "Good" ] }, { "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "bbox":[ 39.655889846499633, -93.968102868870432, 39.713830612484742, -93.867758337184256 ], "name":"New York, MO", "point":{ "type":"Point", "coordinates":[ 39.684860229492188, -93.917930603027344 ] }, "address":{ "adminDistrict":"MO", "adminDistrict2":"Caldwell Co.", "countryRegion":"United States", "formattedAddress":"New York, MO", "locality":"New York" }, "confidence":"High", "entityType":"PopulatedPlace", "geocodePoints":[ { "type":"Point", "coordinates":[ 39.684860229492188, -93.917930603027344 ], "calculationMethod":"Rooftop", "usageTypes":[ "Display" ] } ], "matchCodes":[ "Good" ] } ] } ], "statusCode":200, "statusDescription":"OK", "traceId":"4655cb7ebc1d4b0bb91ef3c047217bbd" }
Complete Sample Code
The following is the complete sample C# code. You must insert your Bing Maps Key.
using System; using System.Net; using System.Runtime.Serialization.Json; namespace RESTServicesJSONParserExample { class Program { static string BingMapsKey = "insertYourBingMapsKey"; 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("\n\n"); } } 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(); } } }