Moshe Stone Moshe Stone - 3 months ago 13
JSON Question

JSON serialization with class inherited from List<T>

I have a class that inherits from

List<T>
and add one more class property

public class DrivenList : List<int>
{
public string Name {get;set;}

private DrivenList() { }

public DrivenList(string name) { this.Nname = name; }
}


When JSON serializing the object using Newtonsoft.Json, I get only the list item. ( [1,2,3] )

Any ideas how to add the
Name
property to the results?

Solved: by adding this attribute to the list

[JsonObject(MemberSerialization = MemberSerialization.Fields)]
public class DrivenList : List<int>

Answer

As far as I know with Newtonsoft all you can do is something like this:

[JsonObject(MemberSerialization = MemberSerialization.Fields)]
public class DrivenList : List<int>
{

    [JsonProperty]
    public string Name { get; set; }

    private DrivenList() { }

    public DrivenList(string name) { this.Name = name; }
}

But this will add you unwanted (maybe) fields.

Personally I will do composition instead of inheritance:

public class DrivenList
{
    public string Name { get; set; }

    public List<int> Items { get; set; }

    private DrivenList() { }

    public DrivenList(string name) { this.Name = name; }
}