0

Looks like no C# JSON serialization framework can deserialize self reference loop.

But why?

Let's imagine that we have this class structure:

public class Person
{
    public string Name { get; set; };
    public City City { get; set; }
}

public class City
{
   public string Name { get; set; }
   public List<Person> Persons { get; set; }
}

and in serialization/deserialization settings we say that if objects are the same put $ref instead of serializing object again

and serialized person will look like this

{
"$id":"1",
"Name":"John",
"City":{
    "$id":"2",
    "Name":"London",
    "Persons":[
        {
           "$ref":"1"
        }
     ]

and on deserialization you are simply creating person with no City then creating City with person and initialize person property with created City

    var person = new Person();
    var city = new City();
    city.Persons = new List<Person>{ person };
    person.City = city;

One explanation I can find was that if you have no empty constructors, you need to create parameters first.

But even if you have one, all serializing frameworks that I can find cannot deserialize it properly.

EDIT: IT CAN BE DESERIALIZED.

I thought that structure in the example is according to my real class structure, my real structure was not deserializing properly, so I didn't try to really serialize/deserialize structure from the example. Then, when I tried it was deserialized fine, so I checked my real structure and the reason why it was not deserializing properly is that I missed setter on property.

1 Answer 1

1

You didn’t show any actual attempts to serialize/deserialize so I don’t know what you’ve tried, but it took me 30s to find out how to do it with System.Text.Json so I suggest you give that a try. It involves configuring the ReferenceHandler option in JsonSerializerOptions

        JsonSerializerOptions options = new()
        {
            ReferenceHandler = ReferenceHandler.Preserve,
            WriteIndented = true
        };

Microsoft page devoted to this topic

Sign up to request clarification or add additional context in comments.

1 Comment

My fault. It's working fine. The structure in the example is not real, I made it according to the real structure, but apparently I'm missing something. I will check what's missing and edit the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.