-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
Description
Given a class that inherits from List<T> with additional custom properties, the JsonSerializer only serializes the List data and not the custom properties.
Reproduction Steps
public class Things : List<string> {
public DateTime BeginTime {get;set;} = DateTime.MinValue;
}
public static void Main() {
Things things = new Things();
things.BeginTime = DateTime.Now;
things.Add("Thing One");
things.Add("Thing Two");
string json = JsonSerializer.Serialize(things);
Console.WriteLine(json); // where has the BeginTime run off to? ["Thing One","Thing Two"]
}
Expected behavior
I would expect both the list data and the custom properties to be serialized. (And, of course, deserialized).
Actual behavior
Only the list data is serialized. No custom properties are serialized.
Regression?
I don't know.
Known Workarounds
One could change their class to use encapsulation rather than inheritance, but that may not make sense in any particular instance/architecture. One should not need to worry about whether their class will de/serialize properly when designing their data objects. Serialization is one of those things that are often hidden (say, when using a WebAPI) so where possible serialization should "just work".
Another workaround would be to create a custom serializer (adapter.. whatever its called).. but that seems pretty heavy-handed for something this trivial.
Configuration
.NET 7.0
Windows 10 22H2 x64
I do not believe this to be specific to this configuration, since the same behavior can be observed on dotnetfiddle.
I have not tried this on Blazor, only .NET 7.0 Console.
Other information
No response