2

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...

dbc
  • 104,963
  • 20
  • 228
  • 340
outfox
  • 126
  • 6
  • 2
    and how it shoud be serialized? list is serialized as json array - so additional property doesn't make sens – Selvin May 27 '22 at 11:08
  • 1
    also read [this](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) – Selvin May 27 '22 at 11:11
  • Should you not rather create the `Foo` class without inheriting from the `List` class. The two properties will then be serialized (and also deserialized if necessary) as normal. – Francois Louw May 27 '22 at 11:21
  • @Selvin Thanks Selvin ,that's a great help. I'll modify my design. – outfox May 27 '22 at 11:24
  • Basically a duplicate of [How can I serialize a property in an inherited ICollection class?](https://stackoverflow.com/q/71688136/3744182) I think, but that has no upvoted or accepted answers. – dbc Jun 09 '22 at 22:43

0 Answers0