I have an ASP .NET 5 project with a Controller and some model classes. The project references Newtonsoft.Json
which is used to support the $type property inside the json response.
This works quite fine until I moved some classes around my project (I think it started with the moving). Simple classes are getting serialized as they should, but when it comes to polymorphism, there happens something strange.
First of all, here is the model class with it's base class: Note: For simplicity I have renamed the classes and properties
[DataContract(Name = "BuildingValue")]
public class DerivedClass : BaseClass
{
public List<AnotherClass> List2 { get; set; } = new();
public List<AnotherClass> List3 { get; set; } = new();
}
public abstract class BaseClass
{
public Guid Prop1 { get; set; }
public uint Prop2 { get; set; }
public List<AnotherClass> List1 { get; set; } = new();
}
I register the Serializer inside my Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
});
And I have a method which generates a List. I have checked several times that the data are valid, so no need to show the List.
Now if I run a request with Postman, the response is as follow:
[
{
"$type": "DerivedClass"
},
{
"$type": "DerivedClass"
},
{
"$type": "DerivedClass"
}
]
even if I serialize without adding options I get something like this:
[{},{},{}]
I absolutely cannot imagine what I have changed which causes this behavior because it worked once. Does anyone have an idea what I am doing wrong?
If you need more code or information, please let me know!