Consider you have:
class ContentRef {
SomeProperty
}
class Content : ContentRef {
SomeOtherProperty
}
class C {
ContentRef someProperty;
List<ContentRef> someList;
}
var someObject = new C { someProperty = new Content(), someList = new List<ContentRef>({new Content()})};
By default both Newtonsoft and System.Text.Json serialize all of the properties of Content in someObject. But clearly, the definition for C says that both are of type A. I want to make sure that in both the case of the direct property A and List that the only thing that gets serialized is A's properties even if you assign B into it.
This happens all of the time in document databases when you have a Ref class for a property that you're setting and you set it to the full class that inherits from the ref class for the rest of the data. You only want the document database to store the ref class's data, not all of the full class because when it's deserialized you only care about the Ref class as defined.
I've got this:
public class StrictTypeContractResolver : DefaultContractResolver
{
private readonly FieldInfo _IsSealedField = typeof(JsonContract).GetField("IsSealed", BindingFlags.Instance | BindingFlags.NonPublic)!;
public override JsonContract ResolveContract(Type type)
{
var resolveContract = base.ResolveContract(type);
_IsSealedField.SetValue(resolveContract, true);
return resolveContract;
}
}
Which works in the direct property case and only serializes the actual defined type. However, I can't figure out how to get it to work on the List type (either a hashset, IList, or IEnumerable). It serializes the entire thing instead of just the List like it should.