I have a generic type that inherit from List, and I want to serialize the extra properties by using System.Text.Json. My code was just like this:
using System.Text.Json;
using System.Text.Json.Serialization;
void Main()
{
var bars = Enumerable.Range(1, 4).Select(i => new Bar { Id = i });
Foo<Bar> foo = new Foo<Bar>(123, bars);
var jsonOption = new JsonSerializerOptions
{
WriteIndented = true
};
var json = JsonSerializer.Serialize(foo, jsonOption);
Console.WriteLine(json);
}
class Foo<T> : List<T>
{
public int Mark { get; set; }//This property can not be seriliazed!!
public Foo(int mark, IEnumerable<T> foos)
{
Mark = mark;
AddRange(foos);
}
}
class Bar
{
public int Id { get; set; }
}
//Output:
//
//[
// {
// "Id": 1
// },
// {
// "Id": 2
// },
// {
// "Id": 3
// },
// {
// "Id": 4
// }
//]
Sadly the preceding code does not serialize the 'Mark' property which I expected...