Domain Objects with Circular or Backwards References In C#, Serialization via JSON and Getting Them Across the Wire

There are always times when your child DOM object references a parent object that contains a list of them children DOM objects that, of have a parent, creating a rather nasty but simply to solve dilemma of circular reference. I’ll cut right down to the chase, as far as domain classes are concerned in .NET, all you have to do is just specify that your DOM class contains references:

[Serializable, DataContract(IsReference = true)]
public class Person ...

As DOM is independent of methods transmitted, whether from or to, and results in the same object and does not matter – I assume you know that already. If you don’t get that, post below – I’ll be happy to help you understand, when I have time.

A typical thing is RestSharp, great library but does not account for these references. Gotta use Newtonsoft.Json, easy enough:

this.YourDomainObject = 
    JsonConvert.DeserializeObject(
         restSharpResponse.Content, 
         new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
This entry was posted in C# and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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