Json.net serialization of custom collection implementing IEnumerable

后端 未结 2 884
独厮守ぢ
独厮守ぢ 2020-12-06 16:44

I have a collection class that implements IEnumerable and I am having trouble deserializing a serialized version of the same. I am using Json.net v 4.0.2.13623

Here

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 17:15

    As of Json.NET 6.0 Release 3 and later (I tested on 8.0.3), this works automatically as long as the custom class implementing IEnumerable has a constructor that takes an IEnumerable input argument. From the release notes:

    To all future creators of immutable .NET collections: If your collection of T has a constructor that takes IEnumerable then Json.NET will automatically work when deserializing to your collection, otherwise you're all out of luck.

    Since the MyTypes class in the question has just such a constructor, this now just works. Demonstration fiddle: https://dotnetfiddle.net/LRJHbd.

    Absent such a constructor, one would need to add a parameterless constructor and implement ICollection (instead of just IEnumerable) with a working Add(MyType item) method. Json.NET can then construct and populate the collection. Or deserialize to an intermediate collection as in the original answer.

提交回复
热议问题