1

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!

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
DirtyNative
  • 2,553
  • 2
  • 33
  • 58
  • 1
    `DataContract` serialization is opt-in. You must mark members to be serialized with `[DataMember]`. See: [json.net does not serialize properties from derived class](https://stackoverflow.com/q/22080387/3744182) and [caliburn.micro serialization issue when implementing PropertyChangedBase](https://stackoverflow.com/q/29200648/3744182). You're doing something a little different here, namely applying `[DataContract]` to a derived class while it is not applied to the base class. Json.NET may be getting confused, and think the properties of the base class are opt-in also. – dbc Nov 23 '21 at 20:54
  • 1
    After marking all properties with `[DataMember]` and the `BaseClass` with `[DataContract]` everything is getting serialized as expected. Thanks a lot for pointing this out. Still confused why it worked once – DirtyNative Nov 23 '21 at 21:05

0 Answers0