Subscribe to the RSS feed then follow me on twitter at @mrlacey (misc) and @wpug (WPDev news)

Wednesday, March 07, 2012

Debugging deserialization errors in JSON.NET

Ever have a problem handling deserialization issues with JSON.NET?
Did you know it has built in functionality to help debug deserialization errors?
Well, it does.

To help debug such scenarios you can do something like this:


   if (!string.IsNullOrEmpty(json))
   {
       var settings = new JsonSerializerSettings
           {
               Error = (sender, args) =>
                       {
                           if (System.Diagnostics.Debugger.IsAttached)
                           {
                                System.Diagnostics.Debugger.Break();
                           }
                       }
           };
 
        result = JsonConvert.DeserializeObject<T>(json, settings);
   }

I find that being able to get into the debugger when something won't deserialize I can quickly and easily identify the cause of the issue.

Hope this is useful to someone

Are you a Windows Phone, Nokia-X (Android) or Asha developer? If so, you could be getting rewards for the apps you build and the success they achieve by joining the DVLUP program.

5 comments:

  1. That is INSANELY helpful. I'm about to have to debug some ugly json issues in Twitterizer and I've been dreading it until this very moment!

    ReplyDelete
  2. Brian4:06 pm

    thank you so much for this, I spent so much time trying to fix my problem and this helped me so much!

    locksmith w8

    ReplyDelete
  3. Nice blog, its great article informative post, thanks for sharing it. Thanks for the information!

    Voip Solution

    ReplyDelete
  4. Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

    ReplyDelete
  5. This is the top Google result for 'newtonsoft json debug deserialisation' - and so it should be! THANK YOU for the great tip.

    ReplyDelete