4

I am using a 3rd party class for Date range handling (Itenso.TimePeriod), and I want to serialize these objects with JSON.Net. There are many fields in this class that I don't want to be serialized, to keep the JSON small. For my own classes I use the [JSonIgnore] attribute, but I don't want to fork this 3rd party component, just to add [JSonIgnore]s to some of its fields. I know the [OnSerializing] callbacks, but these would also require to change the 3rd party class. Of course, I could create some DTO classes that leave out the properties that I don't want to be serialized, but maybe there's a more elegant way?

Heinz Kessler
  • 1,500
  • 11
  • 22
  • 2
    I'd say the best solution is DTO class. But you could create a JsonConverter as well. Here's an example: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm – tukaef Mar 25 '19 at 18:57
  • 1
    [`CustomJsonConverter`](https://www.newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm) would be the way to go, but we can't really answer without a more concrete example. Possibly useful: [Registering a custom JsonConverter globally in Json.Net](https://stackoverflow.com/q/19510532), [How to deserialize a unix timestamp (μs) to a DateTime from JSON?](https://stackoverflow.com/q/19971494/3744182). One approach would be to create a DTO for `TimePeriod` then convert to, and serialize, the DTO inside the converter. – dbc Mar 25 '19 at 19:56
  • The elegant way is working with DTO. Is the flexible way, and the correct one. – Leandro Bardelli Dec 06 '21 at 19:07

0 Answers0