How to serialize/deserialize a custom collection with additional properties using Json.Net

The problem is the following: when an object implements IEnumerable, JSON.net identifies it as an array of values and serializes it following the array Json syntax (that does not include properties), e.g. :

 [ {"FooProperty" : 123}, {"FooProperty" : 456}, {"FooProperty" : 789}]

If you want to serialize it keeping the properties, you need to handle the serialization of that object by hand by defining a custom JsonConverter :

// intermediate class that can be serialized by JSON.net
// and contains the same data as FooCollection
class FooCollectionSurrogate
{
    // the collection of foo elements
    public List<Foo> Collection { get; set; }
    // the properties of FooCollection to serialize
    public string Bar { get; set; }
}

public class FooCollectionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(FooCollection);
    }

    public override object ReadJson(
        JsonReader reader, Type objectType, 
        object existingValue, JsonSerializer serializer)
    {
        // N.B. null handling is missing
        var surrogate = serializer.Deserialize<FooCollectionSurrogate>(reader);
        var fooElements = surrogate.Collection;
        var fooColl = new FooCollection { Bar = surrogate.Bar };
        foreach (var el in fooElements)
            fooColl.Add(el);
        return fooColl;
    }

    public override void WriteJson(JsonWriter writer, object value, 
                                   JsonSerializer serializer)
    {
        // N.B. null handling is missing
        var fooColl = (FooCollection)value;
        // create the surrogate and serialize it instead 
        // of the collection itself
        var surrogate = new FooCollectionSurrogate() 
        { 
            Collection = fooColl.ToList(), 
            Bar = fooColl.Bar 
        };
        serializer.Serialize(writer, surrogate);
    }
}

Then use it as follows:

var ss = JsonConvert.SerializeObject(collection, new FooCollectionConverter());

var obj = JsonConvert.DeserializeObject<FooCollection>(ss, new FooCollectionConverter());

Personally I like to avoid writing custom JsonConverters where possible, and instead make use of the various JSON attributes which were designed for this purpose. You can simply decorate FooCollection with JsonObjectAttribute, which forces serialization as a JSON object rather than an array. You'd have to decorate the Count and IsReadOnly properties with JsonIgnore to prevent them from showing up in the output. If you want to keep _foos a private field, you would also have to decorate it with JsonProperty.

[JsonObject]
class FooCollection : IList<Foo> {
    [JsonProperty]
    private List<Foo> _foos = new List<Foo>();
    public string Bar { get; set; }  

    // IList implementation
    [JsonIgnore]
    public int Count { ... }
    [JsonIgnore]
    public bool IsReadOnly { ... }
}

Serializing yields something like the following:

{
  "_foos": [
    "foo1",
    "foo2"
  ],
  "Bar": "bar"
}

Obviously this only works if you are able to change the definition of FooCollection in order to add those attributes, otherwise you have to go the way of custom converters.


If you also want to keep the contents of the List or collection itself, You could consider exposing property return the list. It has to be wrapping to prevent cyclic issue while serializing:

[JsonObject]
public class FooCollection : List<int>
{
    [DataMember]
    public string Bar { get; set; } = "Bar";
    public ICollection<int> Items => new _<int>(this);
}

public class _<T> : ICollection<T>
{
    public _(ICollection<T> collection) => Inner = collection;    
    public ICollection<T> Inner { get; }    
    public int Count => this.Inner.Count;    
    public bool IsReadOnly => this.Inner.IsReadOnly;    
    public void Add(T item) => this.Inner.Add(item);    
    public void Clear() => this.Inner.Clear();    
    public bool Contains(T item) => this.Inner.Contains(item);    
    public void CopyTo(T[] array, int arrayIndex) => this.Inner.CopyTo(array, arrayIndex);    
    public IEnumerator<T> GetEnumerator()=> this.Inner.GetEnumerator();
    public bool Remove(T item) => this.Inner.Remove(item);    
    IEnumerator IEnumerable.GetEnumerator() => this.Inner.GetEnumerator();
}

new FooCollection { 1, 2, 3, 4, 4 } =>

{
  "Bar": "Bar",
  "Items": [
    1,
    2,
    3
  ],
  "Capacity": 4,
  "Count": 3
}

new FooCollection { 1, 2, 3 }.ToArray() => new []{1, 2, 3}.ToArray()