Subscribe to the RSS feed then follow me on twitter at @mrlacey

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

If you've built Windows Phone or Windows Store apps you can cross-promote them with AdDuplex to get more users.

7 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
  6. Anonymous4:19 pm

    This comment has been removed by a blog administrator.

    ReplyDelete
  7. Great work you have created in this website i really like it Thanks for sharing.

    ReplyDelete