0

Consider the code below. When I try to serialize this by calling the 'SaveToFile' method the property 'Name' doens't get serialized.

Any ideas?

public class Subs
{
    public string Something { get; set; } = "smew";
}

public class Plep : List<Subs>
{

    public string Name { get; set; } = "smew";

    public void SaveToFile(string file)
    {

        using (StreamWriter wrt = new StreamWriter(file))
        {
            wrt.WriteLine(JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All,
                //TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,

            }));
        }
    }
}
  • 1
    How do you expect it to be serialized to JSON? As array or object with properties? These are incompatible and it seems that Newtonsoft falls back to the List/Array. – phuzi Oct 14 '19 at 11:38
  • Why do you even **derive** from list? Usually you don´t need this. Instead just **use** a list, e.g. by exposing a `List`. – MakePeaceGreatAgain Oct 14 '19 at 11:38
  • Looks like a duplicate of [How to serialize/deserialize a custom collection with additional properties using Json.Net](https://stackoverflow.com/q/14383736/3744182) and [How do I get json.net to serialize members of a class deriving from `List`?](https://stackoverflow.com/q/21265629/3744182) and [JSON serialize properties on class inheriting list](https://stackoverflow.com/q/35439335/3744182). – dbc Oct 14 '19 at 17:52

1 Answers1

2

Don't derive you class from List<> as mentioned here.

Change your class to:

public class Plep 
{
public string Name { get; set; } = "smew";
public List<Subs> Subs {get;set;}

public void SaveToFile(string file)
{

    using (StreamWriter wrt = new StreamWriter(file))
    {
        wrt.WriteLine(JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            //TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,

        }));
    }
}
phuzi
  • 12,078
  • 3
  • 26
  • 50
Neil
  • 11,059
  • 3
  • 31
  • 56
  • For now this is the solution i'll be using. It isn't completely what I wanted though, I have to do something else now. I hope to elaborate some more in the near future. – Bas Visscher Oct 14 '19 at 13:05