Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate deserialization attributes from my model classes?

I am currently developing an application that rely heavily on the .NET serializer for converting back and forth between objects and XML. It works fine, but embedding serialization/deserialization attributes directly into my model classes seam like a pretty poor design choice.

Is it somehow possible to sparate these attributes from the class itself? An example of what I would like to achieve can be seen here

Thanks in advance and have a great day

like image 577
Kenneth Brodersen Avatar asked Feb 03 '15 12:02

Kenneth Brodersen


1 Answers

Unfortunately the answer to this isn't as easy and straightforward as you may hope. Serializers sometimes need hints on how to map a text representation of your data to the conceptual object representation (and vice versa). This is often more true of XML than JSON because it is more structured (elements, attributes, namespaces, schema, etc). The EF fluent model builder example you referred to isn't for serialization, it's for mapping to/from a relational schema, which is quite different from XML serialization.

Even tools like JSON.NET have these kinds of attributes, which are necessary when the names of your serialized members don't quite match the properties on your object, and you don't want to write a custom converter.

If the attribute pollution really bothers you, then you can introduce another layer between the models and the XML. You can then have types which contain the attributes and serve the sole purpose of serializing to and from XML, and then use a tool like AutoMapper or ValueInjecter to convert from that layer into your model layer.

I too don't always like attributes polluting my types, for example with MVC model validation attributes and especially for giving hints to EF on how my entity model maps to a relational schema. However this is one instance where I think it can be appropriate, because you get a lot out of it with a pretty minimal amount of code.

There seems to be at least one fluent XML serialization tool out there, but not sure how good it is:

https://fluentlyxml.codeplex.com/

http://trycatchfail.com/blog/post/fluent-xml-serializatione28093introduction.aspx

like image 68
danludwig Avatar answered Oct 23 '22 03:10

danludwig