2

Does YamlDotNet library support Deserialization into existing object rather than creation a new one?
I need it because my object is created through Dependency Injection, so I prefer a way when Deserialization fill (rewrite) all properties into the given object.

I didn't find suitable overloading of the Deserialization method.
Of course, I know I can manually handle YamlMappingNode but simplicity of the Deserialization method is so cute, writing a Copy Constructor for each type isn't an option too. Introducing an intermediate dictionary with properties value is ugly.

Also, I think it can be highly demanded feature.

Brains
  • 594
  • 1
  • 6
  • 18

2 Answers2

1

Although SharpYaml has an ObjectContect.Instance that seems to support deserialization, it is not exposed in any of the public interfaces. It is used internally to deserialize inner elements. I have forked SharpYaml to expose this functionality, and to allow properties of inner objects to be updated rather than the object fully reset.

The forked version is at https://github.com/PeterDavidson/SharpYaml

I have also submitted a pull request; if it gets accepted into the main repo then I will delete the fork.

Edit: This is now included in the core SharpYaml, so you can now use

Deserialize<T>(TextReader reader, object existingObject=null)

Note that this will also allow the existing object to be partly configured - any properties that already have values will be maintained, and only those properties defined in the yaml file will be changed. Any list properties will be added to.

Peter Davidson
  • 404
  • 4
  • 9
  • You can use `ObjectContext.Instance` into your custom Serializer inherited from `ObjectSerializer` in the overrided `CreateOrTransformObject` method. – Brains Apr 20 '15 at 11:34
  • I've seen your commit `Allow Deserialize into an existing object` only now. Thanks for it. – Brains May 14 '15 at 08:34
0

SharpYaml has a property ObjectContext.Instance which is described as:

The instance of an object that will recieve deserialization of its members (in case the instance cannot be created).

Brains
  • 594
  • 1
  • 6
  • 18