Subscribe via RSS

A quick note on interfacing with JSON services via C#

I'm sure there are 100s of ways to manually create classes for JSON objects and then decipher them upon web-service response, but I've just stumbled across a fantastic site called 'json 2 csharp' that creates the classes for you. Just slap in your response (try to get a fully-fleshed out one with as fewer nulls as possible) and it'll generate the class structure.

You can then use the NewtonSoft JsonConvert deserialiser to populate it.

An example

Here's a link: jsontest 'date' example. It produces the following response:

{
   "time": "05:13:02 AM",
   "milliseconds_since_epoch": 1425532382121,
   "date": "03-05-2015"
}

From here, you just copy the entire response and paste it into the text field on the json2csharp site.
Hit 'Generate' and the site will spit out the following:

public class RootObject //rename this!
{
    public string time { get; set; }
    public long milliseconds_since_epoch { get; set; }
    public string date { get; set; }
}

Note that 'RootObject' is a little boring... rename it to 'DateResponse'

Add a helper library to your code to easily pull JSON responses (and POST):

public static class JSONUtilities
{
	public static string GetJSON(string url)
	{
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
		try
		{
			WebResponse response = request.GetResponse();
			using (Stream responseStream = response.GetResponseStream())
			{
				StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
				return reader.ReadToEnd();
			}
		}
		catch (WebException ex)
		{
			WebResponse errorResponse = ex.Response;
			using (Stream responseStream = errorResponse.GetResponseStream())
			{
				StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
				Console.WriteLine(reader.ReadToEnd());
			}
			throw;
		}
	}

	public static Tuple<HttpStatusCode, String> PostJSON(string url, string jsonContent)
	{
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
		request.Method = "POST";

		System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
		Byte[] byteArray = encoding.GetBytes(jsonContent);

		request.ContentLength = byteArray.Length;
		request.ContentType = @"application/json";

		using (Stream dataStream = request.GetRequestStream())
		{
			dataStream.Write(byteArray, 0, byteArray.Length);
		}
		long length = 0;
		try
		{
			using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
			{
				length = response.ContentLength;
				using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
				{
					return new Tuple<HttpStatusCode, string>(response.StatusCode, reader.ReadToEnd());
				}
			}
		}
		catch (WebException ex)
		{
			// Log exception and throw as for GET example above
			Console.WriteLine("ERROR: " + ex.Message);
			throw ex;
		}
	}
}

And now you can bring it all together:

private bool Get()
{
    var result = JSONUtilities.GetJSON("http://date.jsontest.com/");
    var dateResponse = JsonConvert.DeserializeObject<DateResponse>(result);
    Console.WriteLine("Got Response: " + dateResponse.date + " [" + dateResponse.time + "]");
}

Too easy!

avatar

About stevenh

Trains... trains... trains... + Electronics + Japan.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


*

No trackbacks yet.