Created
June 4, 2012 13:05
-
-
Save Dynyx/2868244 to your computer and use it in GitHub Desktop.
Postal code lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class PostalLookup | |
{ | |
public static Postal Find(string countryCode, string postalCode) | |
{ | |
// remove letters from postal code | |
postalCode = Regex.Replace(postalCode, "[^0-9]", ""); | |
if (string.IsNullOrEmpty(postalCode) || postalCode.Length != 4) | |
return null; | |
if (string.IsNullOrEmpty(countryCode)) | |
return null; | |
// create the web request to the GeoNames interface | |
const string geoNamesUrl = "http://ws.geonames.org/postalCodeLookupJSON?postalcode={0}&country={1}"; | |
WebRequest geoNamesRequest = WebRequest.Create(String.Format(geoNamesUrl, postalCode, countryCode)); | |
// make the call | |
WebResponse geoNamesResponse = geoNamesRequest.GetResponse(); | |
// grab the response stream | |
var geoNamesReader = new StreamReader(geoNamesResponse.GetResponseStream()); | |
// put the whole response in a string | |
string geoNamesContent = geoNamesReader.ReadToEnd(); | |
try | |
{ | |
JObject o = JObject.Parse(geoNamesContent); | |
var postal = new Postal | |
{ | |
Code = (string)o["postalcodes"][0]["postalcode"], | |
PlaceName = (string)o["postalcodes"][0]["placeName"], | |
County = (string)o["postalcodes"][0]["adminName1"] | |
}; | |
return postal; | |
} | |
catch | |
{ | |
return null; | |
} | |
} | |
} | |
public class Postal | |
{ | |
public string Code { get; set; } | |
public string PlaceName { get; set; } | |
public string County { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment