LaPointe LaPointe - 2 months ago 24
JSON Question

Serialize a list of derived list

I can't find a way to serialize with JSON.NET a list of derived lists, and I'm starting to wonder if it's even possible. Let me explain the situation with some code.

I've created a new class which is derived from a list of a specific object (tried first with a generic one) and added a string property

NomGroupe
:

public class GroupeActes : List<Acte>
{
public string NomGroupe { get; set; }

public GroupeActes(string nom, List<Acte> liste)
{
NomGroupe = nom;

foreach (var acte in liste)
{
this.Add(acte);
}
}
}


Then, in my code, I've declared a list of this class (
List<GroupeActes> listOfGroupeActes
) and I fill it with data. For the serialization, I use this code:

JsonSerializer serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
using (StreamWriter sw = new StreamWriter(@"listOfGroupeActes.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, listOfGroupeActes);
}


I've tried with and without the
TypeNameHandling.All
parameter and with several combination of Json.net properties and even with DataContract/DataMember.

So far, I only managed to get in my json file either the data of each nested
List<Acte>
without the
NomGroupe
property, or the other way around. But not both, which is what I'd like to have.

Two questions then:


  • Is it even possible?

  • If yes, how can I do it?



Thanks for your help!

Answer

You don't want to inherit from List<T>.

Create a list property instead:

public class GroupeActes
{
    public List<Acte> Actes { get; set; }

    public string NomGroupe { get; set; }

    public GroupeActes(string nom, List<Acte> liste)
    {
        NomGroupe = nom;

        Actes.AddRange(acte);           
    }
}

Lists (and other collection types) get special treatment while serializing. You don't want the collection type's public properties (such as Capacity and Count) in your output, so the property you added through inheritance won't be serialized either.

A collection is serialized like this:

if o is IEnumerable
    foreach object s in o
        serialize o

So the serializer won't even look at your enumerable's properties.

Comments