views:

82

answers:

3

Is it possible to deserialize object properties, using any of the standard serializers, without creating a new object?

Problem is, the objects in question are very complex (they can only be created by a special factory, and their types are dynamically generated at runtime), but they have some known properties, which I would like to store in external file (preferably xml, but binary is OK too), and later (possibly after application is restarted), I want stored properties to be set back to the object I provide.

It seems all the standard serializers can only generate a new object for me (which also requires a public parameterless constructor), from which I would have to manually assign all the properties. This is not much different from manual serialization, which I would like to avoid, since a set of serialized properties is quite large and is probably going to change a few times during project lifetime. At this point I'm quite close to writing my own lightweight serializer, but maybe someone could suggest a more standard way of doing such things?

+1  A: 

protobuf-net has a Serializer.Merge method that lets you deserialize into an existing instance. Only values found in the stream are written (it doesn't wipe the object).

Not Microsoft, but pretty stable.

To expand on this; getting robust serialization that handles all the common scenarios is (I know from painful experience) a lot of work. My recommendation would definitely be to re-use existing code where possible. protobuf-net seems to offer everything you need; the current binaries simply require you to decorate your class (very similar to [DataContract] from WCF - in fact it even supports [DataContract] / [DataMember]), but work is in place to allow it to work even against POCO - so you can use it with types outside your control.

Marc Gravell
Doesn't that work on the field level, instead of the property level as requested?
Lucero
@Lucero - it works on both fields and properties; it depends what you tell it to do.
Marc Gravell
Thank you for an interesting link, but I would prefer not to involve a whole new third party component for such a rather simple task. Also the downside is that it's not xml.
Chriso
A: 

You can implement your own flexible "serializer" to handle this. Reflection provides you with everything you need.

Lucero
A: 

You could use the FormatterServices.PopulateObjectMembers method, which seems to be exactly designed for this task...

Thomas Levesque
By that point, you will already have had to parse the stream to get the values into `object` s, *and* obtained the `MemberInfo` s, *and* dealt with all the complexities of sub-data etc. To be honest, simply having a method to *set* the values offers little - at that point you could just use reflection.
Marc Gravell