views:

27

answers:

1

Hi people.

I am doing some work with C#, AJAX and JSON and am getting a Self referencing loop error. I am managing to get around this using the JsonIgnore attribute, but I was wondering if someone can give me a proper explanation as to what is actually happening here.

Many thanks.

Dave

+1  A: 

We don't get much detail on your problem, but it's probably exactly what you're describing: a loop of self-reference, or a circular chain of references.

Say you've got a variable of the type User that has a property public UserImage Image. Now, say the type UserImage has a property User that references back to the user.

In your .NET code, it's just that. myImage.User gives yo uthe user, myUser.Image gives you the image. But imagine you want to serialize myUser (into JSON, say). Then you have to cycle every property of User and serialize that, recursively. The serializer would start off like this

{ "ID": 1, "Image": { ...

now it has to serialize the user image. And remember UserImage has the variable "User".

{ "ID": 1, "Image": { "Path": "image.src", "User": {

but the user is the very same user that we're trying to reference

{ "ID": 1, "Image": { "Path": "image.src", "User": { "ID": 1, "Image":

now we have to serialize the image for that user, but that, again, is the same image as before:

{ "ID": 1, "Image": { "Path": "image.src", "User": { "ID": 1, "Image": { "Path": "image.src", "User": { "ID": 1, "Image": { "Path": "image.src", "User": { "ID": 1, "Image": { "Path": "image.src", "User": 

so we never reach an end product if we're constantly serializing a circular reference.

David Hedlund
Thanks - that's exactly what I was looking for, just a simple explanation of what is actually going on. Many thanks.
Dave