Json and Circular Reference Exception

ahsteele picture ahsteele · Jan 5, 2010 · Viewed 37.7k times · Source

I have an object which has a circular reference to another object. Given the relationship between these objects this is the right design.

To Illustrate

Machine => Customer => Machine

As is expected I run into an issue when I try to use Json to serialize a machine or customer object. What I am unsure of is how to resolve this issue as I don't want to break the relationship between the Machine and Customer objects. What are the options for resolving this issue?

Edit

Presently I am using Json method provided by the Controller base class. So the serialization I am doing is as basic as:

Json(machineForm);

Answer

Aaronaught picture Aaronaught · Jan 5, 2010

Update:

Do not try to use NonSerializedAttribute, as the JavaScriptSerializer apparently ignores it.

Instead, use the ScriptIgnoreAttribute in System.Web.Script.Serialization.

public class Machine
{
    public string Customer { get; set; }

    // Other members
    // ...
}

public class Customer
{
    [ScriptIgnore]
    public Machine Machine { get; set; }    // Parent reference?

    // Other members
    // ...
}

This way, when you toss a Machine into the Json method, it will traverse the relationship from Machine to Customer but will not try to go back from Customer to Machine.

The relationship is still there for your code to do as it pleases with, but the JavaScriptSerializer (used by the Json method) will ignore it.