Skip to content

System.Text.Json.JsonSerializer.Serialize does not correctly serialize classes that inherit from List<T> #79106

@DWAK-ATTK

Description

@DWAK-ATTK

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions