Handling circular reference with Newtonsoft JSON
18,390
Newtonsoft.Json can have the following config
JsonSerializerSettings sets = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var ser = JsonSerializer.Create(sets);
you might want to do that.
Author by
mimo
Updated on June 28, 2022Comments
-
mimo almost 2 years
My model class look like 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 object, but getting
StackOverflowException
. I have tried to callJsonConvert.SerializeObject(model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
as well as
JsonConvert.SerializeObject(model, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
Both calls resulted in
StackOverflowException
. Any idea how to serializeModelType
instance?EDIT:
Example of instance, which fails to serialize:
{ Name: "Child", SuperType: { Name: "Parent", SuperType: null, SubTypes: [{ Name: "Child", SuperType: { Name: "Parent", SuperType: null, SubTypes: [{Name: "Child", ...}] }, SubTypes: [] }] }, SubTypes: [] }
EDIT2:
By further looking into the issue (according to all SO Q&A, setting either
ReferenceLoopHandling.Ignore
orPreserveReferencesHandling.Objects
should work) I have found out that- Child is unique object instance
- Child.SuperType (Parent) is unique object instance
- Child.SuperType.SubTypes[0] (Child) is unique object instance, not a reference to (1.)
- Child.SuperType.SubTypes[0].SuperType (Parent) is unique object instance, not a reference to (2.)
- And so on...
I think, something went wrong during the object creation (out of my code) and this created infinite chain of objects. I am not sure if this is even possible to handle just by
JsonSerializerSettings
. -
mimo about 8 yearsI have tried it, but it is not working for me. Still getting
StackOverflowException
. -
Avi Fatal about 8 years@mimo - did you look here? stackoverflow.com/questions/25853407/…
-
mimo about 8 yearsI have looked at question and tried to use same
JsonSerializerSettings
as in proposed answer, but it was not working for me. Most of the solutions states, thatPreserveReferencesHandling = PreserveReferencesHandling.Objects
should handle the case, but it is not working in my case.