Consider the following program: (.NET Fiddle Link)
public class Program
{
public static void Main()
{
var carsa = new ListOfCarsA();
carsa.Cars.Add("Toyota");
carsa.Cars.Add("Lexus");
Console.WriteLine(JsonConvert.SerializeObject(carsa, Formatting.Indented));
var carsb = new ListOfCarsB();
carsb.Add("Nissan");
carsb.Add("Infiniti");
Console.WriteLine(JsonConvert.SerializeObject(carsb, Formatting.Indented));
}
}
public class ListOfCarsA
{
public string CollectionName { get { return "CarsA"; } }
public List<string> Cars { get; set; }
public ListOfCarsA()
{
Cars = new List<string>();
}
}
public class ListOfCarsB : List<string>
{
public string CollectionName { get { return "CarsB"; } }
}
This then outputs the following:
{ "CollectionName": "CarsA", "Cars": [ "Toyota", "Lexus" ] }
And
[ "Nissan", "Infiniti" ]
Why does the property CollectionName
not get serialised and output CarsB
, but the same property on the ListOfCarsA
results in CarsA
being serialised?
What is the solution to this problem - How could I have a class similar to ListOfCarsB
but still have any extra members serialised? I have tried using the attributes [JsonProperty("CollectionName"]
and [JsonRequired]
but these seem to do nothing.