4MK Mobile Dev Blog

Adventures in Mobile Development

Quick tip: Getting your JSON out of a WebException

When prototyping out a recent project, I ran into a new issue that I hadn’t seen before, a web service that sent back both a non 200 error code, but also returned relevant JSON data.

The problem happens when trying to get the JSON data about the error.  Since a non-200 Response has been returned you can no longer use the following code:

   1:  void wc_DownloadStringCompleted(object sender, 
   2:      DownloadStringCompletedEventArgs e)
   3:  {
   4:       var jsonContent = e.Result;
   5:       //Do Stuff Here
   6:  }

So the first thing you have to do is check for the Error property and deal with it appropriately.  Luckily for us the Error property has a reference to the actual Response which we can use to get the information we want like so:

   1:  void wc_DownloadStringCompleted(object sender, 
   2:      DownloadStringCompletedEventArgs e)
   3:  {
   4:      string content = string.Empty;
   5:   
   6:      if (e.Error != null)
   7:      {
   8:          var we = e.Error as WebException;
   9:          var stream = we.Response.GetResponseStream();
  10:          content = new StreamReader(stream).ReadToEnd();
  11:      }
  12:      else
  13:          content = e.Result;
  14:   
  15:      //Do Stuff Here
  16:  }

Of course you’ll need to do more error checking that this and make sure that the response code that you want is actually the one you are receiving, but this shows the just of what our solution was.

No Responses to “Quick tip: Getting your JSON out of a WebException”

RSS feed for comments on this post. TrackBack URL

Leave a Response