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 call
JsonConvert.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 serialize ModelType
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
or PreserveReferencesHandling.Objects
should work) I have found out that
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
.
Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match.
Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System.
Text. Json is much faster than the Newtonsoft. Json.
Text. Json library is included in the runtime for . NET Core 3.1 and later versions. For other target frameworks, install the System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With