/ Published in: C#
URL: http://blog.brynildsen.com
See my blog
Expand |
Embed | Plain Text
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 // 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; } }
You need to login to post a comment.
