Handle with care, Json Serialization when SharePoint Object Model’s Objects in the code

My team went crazy with the generic error message that they were getting while trying to Serialize an object created of some POCO. One of them even lost good whole day trying to troubleshoot what exactly is the issue.

The serializer is one of the best in business for .Net , the Newtonsoft.Json.JsonConvert.

And the error message they were getting is

“An unhandled exception of type ‘System.StackOverflowException’ occurred in mscorlib.dll”

which hardly express any means of the cause. This error message is thrown when following piece of code is getting executed.

 JsonConvert.SerializeObject(MyEntity, Newtonsoft.Json.Formatting.Indented);

Finally I figured it out that one of the newly added Properties of MyEntity’s class causing the issue.

The newly added Property is of SPUser field.  So the entity class looked like following,

   public class MyEntity

{

public string Name { get; set; }

public string LoginName { get; set; }

public SPUser User { get; set; }

}

So the issue with the Serializer unable to serialize the instance of SPUser. The when I checked the serializer is unable to serialize SPFieldUserValue and SPFieldUserValueCollection as well.

Workaround :

Anyway fortunately I did not want this field necessarily be in the Json that I was getting.

So I decorated each of those fields with [JsonIgnoreAttribute] attribute. Doing that I had to import the Newtonsoft.Json with using directive. That made my entity class look like ,

   public class MyEntity

{

public string Name { get; set; }

public string LoginName { get; set; }

[JsonIgnoreAttribute]

public SPUser User { get; set; }

}

In conclusion, even if you use more improved serializer like Newtonsoft.json, you should be very careful about what you are trying to serialize and desterilize especially when you are dealing with SharePoint Object model’s classes.

Advertisements

One thought on “Handle with care, Json Serialization when SharePoint Object Model’s Objects in the code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s