#StackBounty: #c# #.net #serialization #json.net #nullreferenceexception Debug JsonConvert.SerializeObject and object reference not set…

Bounty: 50

I cant seem to figure out why the method "sometimes" cause this null reference exception. I run the code on my localhost and it works fine when this appears for some users. When I restart the site it also goes away on the server.

My question is how can I debug this? Its taking a .NET object and trying to serialize it but I cant tell which property is causing this issue.

Method

 public static string ToJSON(this object o)
        {
            return JsonConvert.SerializeObject(o, new JsonSerializerSettings
            {
               ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }

Exception

     at System.Text.StringBuilder.Append(Char value)
   at Newtonsoft.Json.JsonTextWriter.WriteEnd(JsonToken token)
   at Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type)
   at Newtonsoft.Json.JsonWriter.WriteEndObject()
   at Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type)
   at Newtonsoft.Json.JsonWriter.AutoCompleteAll()
   at Newtonsoft.Json.JsonTextWriter.Close()
   at Newtonsoft.Json.JsonWriter.Dispose(Boolean disposing)
   at Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose()
   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, JsonSerializerSettings settings)
   at Tournaments.Common.Extensions.ObjectExtensions.ToJSON(Object o)

Try/Catch

I tried the below and the JavascriptSerializer throws the error A circular reference was detected while serializing an object of type 'Tournaments.Models.Events.EventModel'. However I dont know what object has this EventModel, which could be multiple.

<script type="text/javascript">
        @{ 

            string model = null;
            try
            {
                model = Model.Designer.ToJSON();
            }
            catch (Exception ex )
            {
                model = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.Designer);
            }
            }
            app.viewModel.members.bracket.init(@Html.Raw(model));
    </script>


Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.