posted on
Thursday, March 27, 2008 11:03 PM |
In an attempt to avoid anything I'm actually suppose to be doing right now, I fixed the source for the Google VS Live application. As expected, Google tweaked their return call which broke the JSON serialization. I hopefully made it a tad more hardened now.
Source: c#
Demo: http://peacelovecode.com/search
Updated Source from my GoogleSearch.cs class:
// code based off http://blog.yuvisense.net/2006/12/30/calling-google-ajax-search-api-from-c/
// JSON code from http://www.codeplex.com/Json
public static GoogleSearchResults Search(string apiKey, string query, bool largeQuery)
{
WebRequest wrq = WebRequest.Create(string.Format("http://www.google.com/uds/GwebSearch?" +
"callback=GwebSearch.RawCompletion" +
"&context=0&lstkp=0&rsz={2}&hl=en&" +
"sig=8656f49c146c5220e273d16b4b6978b2&" +
"q={0}&key={1}&v=1.0", query, apiKey, largeQuery ? "large" : "small"));
WebResponse wrs = wrq.GetResponse();
StreamReader sr = new StreamReader(wrs.GetResponseStream());
StringBuilder sb = new StringBuilder();
while (!sr.EndOfStream)
sb.Append(sr.ReadLine());
int removeIndex = sb.ToString().IndexOf("}]");
sb.Remove(removeIndex, sb.Length - removeIndex);
sb.Append("}]}"); // need to keep the JSON struct intact
string result = Regex.Replace(sb.ToString(), "GwebSearch.RawCompletion\\('\\d+',", string.Empty);
result = HackUtf8ToUnicode(result);
return JavaScriptConvert.DeserializeObject<GoogleSearchResults>(result);
}
private static string HackUtf8ToUnicode(string utf8)
{
utf8 = Regex.Replace(utf8, "\\\\u003C", "<", RegexOptions.IgnoreCase);
utf8 = Regex.Replace(utf8, "\\\\u003E", ">", RegexOptions.IgnoreCase);
return Regex.Replace(utf8, "\\\\u0026", "&", RegexOptions.IgnoreCase);
}