Given two classes as follows:
class ListCollection : List<int>
{
}
[Serializable]
class PrivateListCollection: ISerializable
{
private List<int> list = new List<int>();
public void Add(int value)
{
list.Add(value);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("items", list);
}
}
I get after adding 1,2,3 to each of them and serializing using JsonConvert.SerializeObject this:
ListCollection: [1,2,3]
PrivateListCollection: {"items":[1,2,3]}
The question is whether it's possible to get the serialization result of PrivateListCollection as [1,2,3] (without the "items" or whatever in front of it)?
An POCO cannot serialize itself as a JSON array by implementing
ISerializablebecause a JSON array is an ordered sequence of values, whileSerializationInforepresents a collection of name/value pairs -- which matches exactly the definition of a JSON object rather than an array. This is confirmed by the Json.NET docs:To serialize your
PrivateListCollectionas a JSON array, you have a couple of options.Firstly, you could create a custom
JsonConverer:And then either add it to
PrivateListCollectionlike so:Or add it to
JsonSerializerSettingslike so:Demo fiddle #1 here.
Secondly, you could make
PrivateListCollectionimplementIEnumerable<int>and add a parameterized constructor taking a singleIEnumerable<int>parameter like so:Having done so, Json.NET will see
PrivateListCollectionas a constructible read-only collection which can be round-tripped as a JSON array. However, based on the fact that you have named your typePrivateListCollection, you may not want to implement enumeration.Demo fiddle #2 here.