Parse Json in MonoDevelop with C#

I need to consume Json in an iPhone project and for what ever reason, I’m <still> unable to get the preferred NewtonSoft.Json library to work in a MonoDevelop Project… thus, I’m giving System.Json a whirl.

My end point call with an appended UISearchBar value appended looks something like this:

var request = HttpWebRequest.Create (string.Format (@”your url here” + HomeScreen.SearchCriteria));
request.ContentType = “application/json”;
request.Method = “POST”;

The Json coming back down the wire looks like this.

{“key”:”my api key”,”success”:”yes”,”zips”:[{“zip_code”:”34677″,”city”:”Oldsmar”,”county”:”PINELLAS”,”state”:”FL”,”area_code”:”727\/813″,”latitude”:”28.042768″,”longitude”:”-82.679542″,”csa_name”:””,”cbsa_name”:”Tampa-St. Petersburg-Clearwater FL”,”region”:”South”,”time_zone”:”5″} ]}

Getting to the single name/value pairs is straightforward, to reach the the values in the array you’ll need to walk it on down… [“zips”][index][“key”]:

// Handle HTTP Request and HTTP Response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {

// dump any errors into the results container
if (response.StatusCode != HttpStatusCode.OK) {
Console.WriteLine(“Error fetching result. Server returned status code: ” + response.StatusCode + “\r\n”);
}

// catch the response and dump into the result text container
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
string content = reader.ReadToEnd ();

System.Json.JsonValue j = System.Json.JsonArray.Parse(content);
JsonValue result = j as JsonObject;

// parsing out simple name/val pairs

Console.WriteLine(“Key… ” + (string)result[“key”] + “\r\n”);
Console.WriteLine(“Success… ” + (string)result[“success”] + “\r\n”);

// parsing out of the array
Console.WriteLine(“Zip Code… ” + (string)result[“zips”][0][“zip_code”] + “\r\n”);
Console.WriteLine(“City… ” + (string)result[“zips”][0][“city”] + “\r\n”);

}}

Hope this helps someone.