I have a .NET class which represents a RPC method call, like this:
class MethodCall
{
public string MethodName { get; set; }
public Collection<object> Arguments { get; set; }
}
I want to serialize a Collection<MethodCall>
to YAML. I'm using YamlDotNet to achieve this.
By default, YamlDotNet will serialize these objects like this:
methodName: someName
arguments:
- arg1
- arg2
- ...
I would like to simplify the resulting YAML to:
someName:
- arg1
- arg2
Is there any easy way to achieve this? Please note that the arguments can be complex objects (i.e. not simple scalars).
You can achieve this by registering an implementation of
IYamlTypeConverter
that performs the conversion that you need.Here's a possible implementation:
The converter needs to be registered into the
SerializerBuilder
andDeserializerBuilder
through theWithTypeConverter
method. Note that YamlDotNet does not provide us with a way to call the (de)serializer recursively, so we have to set some public properties as a workaround. This is not as clean as it could be, but still works: