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

3 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. This is the top Google result for 'newtonsoft json debug deserialisation' - and so it should be! THANK YOU for the great tip.

    ReplyDelete
  3. This was awesome! Thank you!

    ReplyDelete

I get a lot of comment spam :( - moderation may take a while.