Following on from my post about using Google Local Search from C#, I thought I’d try to improve it. Deserializing the JSON data ended up with some ugly typecasts and manipulation of Dictionarys. The first thing to notice is that the JavaScriptSerializer class has a Deserialize<T> method so all that is needed is a class to hold the returned data. Here’s a simple implementation of this.
public class Results { public double lat; public double lng; } public class ResponseData { public Results[] results; } public class LocalSearchData { public ResponseData responseData; }
OK, I know, there’s a bit of a lack of OO encapsulation going on there but it seems like public fields with names matching the data returned from the JSON are required. They can be replaced with properties, but these must have getters and setters so this doesn’t really buy you much except to stop FxCop moaning at you.
Then the deserializing code looks much nicer
LocalSearchData searchData = serializer.Deserialize<LocalSearchData>(response); latitude = searchData.responseData.results[0].lat; longitude = searchData.responseData.results[0].lng;
This still isn’t perfect. We have to use the same names as used in the JSON, which doesn’t really match up with .NET naming conventions and we have a class hierarchy that doesn’t really serve a purpose. It looks like the JavaScriptConverter class might help out here but that’s something to look at another day. Another alternative might be to just use these classes for moving the data into yet another class that has a better interface.
No comments:
Post a Comment