JSON Serialization and Circular Reference Error !


I have a table that references a child table with reference to parent (!), I am using LINQ to SQL, for a paricular scenario, when I want to serialize my result using Json(obj) in my controller code, I got an error saying.. “A circular reference was detected while serializing an object of type..”

This issue is very well explained by Rick Strahl in his blog (link here)

If we are using WCF services, setting SerializationMode of the data context to “Unidirectional” would do the trick. In my case I was using MVC and it was a controller action invoke from javascript!! Also I did not want to try setting the Access Level to internal because I was not sure whether I get deep serialization if I do that! (did not try, because I was half convinced that It may not work for me)

Issue was Json() call in my controller to convert my object to Json and send back as JsonResult… So I ended up serializing it in my biz layer, biz layer method now returned a Json String, changed my controller to return ActionResult/ContentResult and used Content(jsonString) to send back a ContentResult.

It worked because Javascript library expected a Json Literal and it got that. All is good for now!

One comment

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