Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json and Circular Reference Exception

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); 
like image 445
ahsteele Avatar asked Jan 04 '10 23:01

ahsteele


People also ask

What is circular reference exception C#?

Circular reference occurs when two or more interdependent resources cause lock condition. This makes the resource unusable. To handle the problem of circular references in C#, you should use garbage collection.

What are circular references in Javascript?

A circular reference occurs if two separate objects pass references to each other. In older browsers circular references were a cause of memory leaks. With improvements in Garbage collection algorithms, which can now handle cycles and cyclic dependencies fine, this is no longer an issue.

What is a circular object reference?

A circular reference occurs when one heap variable contains a reference to a second heap variable, and the second one contains a reference back to the first. For instance, if A is an object, and somewhere in A, there is a reference to B, and within B is a reference back to A, there is a circular reference.


1 Answers

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.

like image 96
Aaronaught Avatar answered Sep 28 '22 08:09

Aaronaught