I have a data model made of a TransformationPlanModel
which in turn contains an IEnumerable<TransformationModel>
. TransformationPlanModel
is the root data transfer object. TransformationModel
is an abstract base class for other transformation models.
Snipped code for TransformationPlanModel
:
public class TransformationPlanModel
{
// snip
public IEnumerable<TransformationModel> Transformations { get; set; }
}
Snipped code for TransformationModel
:
public abstract class TransformationModel
{
//snip
public string Key { get; set; }
}
One of concrete transformation models is RemoveRowsTransformationModel
:
public class RemoveRowsTransformationModel : TransformationModel
{
public const string KeyConst = "removeRows";
public int TopRowsCount { get; set; }
public int BottomRowsCount { get; set; }
public RemoveRowsTransformationModel()
{
Key = KeyConst;
}
//snip
}
I've written a custom JsonConverter
which converts the TransformationModel
inheritance tree. The implementation of JsonWrite
method is:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject.FromObject(value, serializer).WriteTo(writer);
}
The custom converter is used in an ASP.NET Core API application and is added to the services in the Startup.ConfigureServices
method like so:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new TransformationConverter());
});
When a TransformationPlanModel
is returned as a response from an API endpoint and is serialized, a Newtonsoft.Json.JsonSerializationException
is thrown containing the message: "Self referencing loop detected with type '(...).RemoveRowsTransformationModel'". What causes this exception? I fail to see where the self referencing loop is. I don't know if it matters, but I'm using .NET Core 2.0 Preview 1.
Interestingly enough, when an overload of JObject.FromObject
without the serializer parameter is used in the WriteJson
method, it works properly:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject.FromObject(value).WriteTo(writer);
}
This however resets the serialization settings, like camel case property naming. I've also tried ignoring the circular references in Json.Net settings, but no transformations are serialized then.