Have you ever tried to return a collection of items via Web API that contains relationships that ends up in a reference loop. A reference loop is where one object references another object that references the object that referenced it. Did you get all that? Many people run into this serialization issue when returning Entity Framework collections that have relationships that end up in a reference loop. I'll rant on this in another blog post.

For now please consider the following code.

public IEnumerable<Person> Get()
    var parent = new Person { Name = "John Smith" };
    var child1 = new Person { Name = "Bob Smith", Parent = parent };
    var child2 = new Person { Name = "Suzy Smith", Parent = parent };
    parent.Children = new[] { child1, child2 };

    return new[] { parent, child1, child2 };

You'll notice that it has a reference loop with the child and the parent. When Json.NET attempts to serialize the collection you'll get error message that goes something like this.

Self referencing loop detected for property 'Parent' with type 'Person'. Path '[0].Children[0]'.

If you do any Googling or Binging then you'll find there is a really common "fix" to the problem. People will suggest you configure the serializer with the following setting.

// Setting this to prevent self referencing loop issue...
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

After setting this you may expect to get back a list of people something like.

  1. John Smith
  2. Bob Smith
  3. Suzy Smith

However what you really get is the following.

  1. John Smith
    1. Bob Smith
    2. Suzy Smith
  2. null
  3. null

Here is the actual JSON return from the Web API.

    "$id": "1",
    "Children": [
      { "$id": "2", "Children": null, "Name": "Bob Smith", "Parent": { "$ref": "1" }},
      { "$id": "3", "Children": null, "Name": "Suzy Smith", "Parent": { "$ref": "1" }}
    "Name": "John Smith",
    "Parent": null
    "$ref": "2"
    "$ref": "3"

This will not be a problem if you are using Json.NET to deserialize the object but if you are doing any manually parsing it could get very difficult. Just be aware that your objects get serialized in the order in which they are found during processed of the object graph. Here are a few StackOverflow questions about the issue.

Rock on and Become Epic!