Circular link handling with Newtonsoft JSON

My model class is as follows:

public class ModelType
{
    public string Name { get; set; }
    public ModelType SuperType { get; set }
    public IEnumerable<ModelType> SubTypes { get; set; }
}

I am trying to serialize an object, but I am getting StackOverflowException. I tried to call

JsonConvert.SerializeObject(model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

and

JsonConvert.SerializeObject(model, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Both calls led to StackOverflowException. Any idea how to serialize an instance ModelType?

EDIT

An example of an instance that cannot be serialized:

{
    Name: "Child",
    SuperType: {
        Name: "Parent",
        SuperType: null,
        SubTypes: [{
                Name: "Child",
                SuperType: {
                    Name: "Parent",
                    SuperType: null,
                    SubTypes: [{Name: "Child", ...}]
                },
                SubTypes: []
        }]
    },
    SubTypes: []
}

EDIT2

Further studying the problem (in accordance with all SO Q & A, tuning ReferenceLoopHandling.Ignoreor PreserveReferencesHandling.Objectsshould work), I found that

  • A child is a unique instance of an object
  • Child.SuperType (parent) - a unique instance of the object
  • Child.SuperType.SubTypes [0] (Child) - a unique instance of the object, not a reference to (1.)
  • Child.SuperType.SubTypes [0] .SuperType (Parent) - a unique instance of the object, not a reference to (2.)
  • Etc...

, - ( ), . , JsonSerializerSettings.

+4
1

Newtonsoft.Json

 JsonSerializerSettings sets = new JsonSerializerSettings
    {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
    };

    var ser = JsonSerializer.Create(sets);

.

+4

All Articles