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
ISerializable
because a JSON array is an ordered sequence of values, whileSerializationInfo
represents 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
PrivateListCollection
as a JSON array, you have a couple of options.Firstly, you could create a custom
JsonConverer
:And then either add it to
PrivateListCollection
like so:Or add it to
JsonSerializerSettings
like so:Demo fiddle #1 here.
Secondly, you could make
PrivateListCollection
implementIEnumerable<int>
and add a parameterized constructor taking a singleIEnumerable<int>
parameter like so:Having done so, Json.NET will see
PrivateListCollection
as 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.