I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used
JsonConvert.SerializeObject
I had this exception and my working solution is Easy and Simple,
Ignore the Referenced property by adding the JsonIgnore attribute to it:
[JsonIgnore]
public MyClass currentClass { get; set; }
Reset the property when you Deserialize it:
Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
{
Source.MyClass = item;
}
using Newtonsoft.Json;
C# code:
var jsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);
var filePath = @"E:\json.json";
File.WriteAllText(filePath, jsonString);
Use this in WebApiConfig.cs
class :
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Please also make sure to use await and async in you method. You can get this error if your object are not serialized properly.
ReferenceLoopHandling.Error
(default) will error if a reference loop is encountered. This is why you get an exception.ReferenceLoopHandling.Serialize
is useful if objects are nested but not indefinitely.ReferenceLoopHandling.Ignore
will not serialize an object if it is a child object of itself.Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});
Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.
Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Pick what makes sense for the object you are serializing.
Reference http://james.newtonking.com/json/help/
My Problem Solved With Custom Config JsonSerializerSettings:
services.AddMvc(
// ...
).AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Serialize;
opt.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
});