I created my own List class, which supports a set of item identifiers for the following reasons:
public class MyCustomList : List<ItemWithID> { private HashSet<int> itemIDs = new HashSet<int>(); public MyCustomList() { } [JsonConstructor] public MyCustomList(IEnumerable<ItemWithID> collection) : base(collection) { itemIDs = new HashSet<int>(this.Select(i => i.ID)); } public new void Add(ItemWithID item) { base.Add(item); itemIDs.Add(item.ID); } public new bool Remove(ItemWithID item) { var removed = base.Remove(item); if (removed) { itemIDs.Remove(item.ID); } return removed; } public bool ContainsID(int id) { return itemIDs.Contains(id); } }
I want to deserialize this list from a simple JSON array, for example:
JsonConvert.DeserializeObject<MyCustomList>("[{ID:8},{ID:9}]");
this will cause JSON.NET to call only the empty constructor, so the itemID list will remain empty. Also, the Add method is not called.
How JSON.NET adds items to the list, so I can add logic to this place.
(we are talking about deserialization without properties that should be constant in the json string, so the proposed duplicate question has nothing to do with this)
Jan s source share