C # Xml serializing objects using IEnumerable

whenever I try to serialize an object that has an IEnumerable collection, I get a big dirty error saying that it cannot serialize it because it is an interface. Now I understand why this happens, but for me other questions arise. For example, if I intend to have collections inside my objects, and I want to serialize them, I need to refer to

  • Using List <>, CollectionBase, ReadOnlyCollectionBase in my objects.
  • Creating objects that implement the IXmlSerializable interface.
  • Making classes using awful attributes.
  • Writing your own serializer.

What is the best practice?

+4
source share
2 answers

Speaking as the author of a serializer, I know for sure why it is very difficult to reliably work only with IEnumerable<T> , especially for receive-only properties. You can try IList<T> (although this would not surprise me if he wanted to get a specific type, for example List<T> / T[] ), but I suspect that the real problem is that you are trying to use one a model for performing two actions, and are unhappy that they have to compromise to do this.

Great: if you don’t want to compromise your domain model, write a separate DTO model that is used for serialization, and simply map between them. This is usually trivial and will allow the serializer and domain models to succeed on the same job. It will also help a lot when you need a "version" of the system or enter another serializer (JSON, protobuf, etc.).

Return your bullets:

  • I suspect any particular type of list (even your own) using Add , etc. will work
  • I do not recommend this to anyone - it hurts to do it reliably
  • nothing to guess about attributes; again, I suspect that your complaint concerns the assignment of your domain model - like this: fine, do not do this - have a separate model; you can do all this at runtime, but it works a lot more (see XmlAttributeOverrides , but watch out for assembly XmlAttributeOverrides if you do)
  • Do not underestimate how much work; the basics are seductively easy; but non-trivial scenarios can be cruel.
+6
source

To use an interface or derivation classes, you MUST use the XmlSerializer constructor (Type Type, Type [] extraTypes).

In extraTypes, you SHOULD include all possible classes that can implement interfaces in your classes.

0
source

Source: https://habr.com/ru/post/1399436/


All Articles