2

I'm looking to find a clean method of customising the output from YamlDotNet serializer.

I have the following POCO:

public class MyClass{
  public string Foo { get;set; }
  public Dictionary<string, string> Bar { get;set; }
}

If I set values on it like

var class = new MyClass{ Foo = "bla" };
class.Bar["key1"] = "val1";
class.Bar["key2"] = "val2";

and serialize this then I will get the results:

Foo: bla
Bar:
  key1: val1
  key2: val2

However, what I need to get is

Foo: bla
key1: val1
key2: val2

I can't add key1, key2 etc as properties of MyClass as they are unknown until runtime (both the value and the number of keys). Is there a way that I can do this using YamlDotNet?

I've considered using reflection to convert everything in MyClass to a Dictionary<string, object> but would prefer a cleaner implementation.

Is there any way that I can control serialization to this degree?

Fermin
  • 34,961
  • 21
  • 83
  • 129
  • In your desired solution, how will the desierialzer know, where to deserialize `key1: val1`? – lokusking Jun 29 '16 at 09:37
  • @lokusking - I'm only worried about serlialization for this. It's to generate RAML so it's only outputting data rather than consuming it. – Fermin Jun 29 '16 at 09:42

1 Answers1

0

A simple solution is to implement IDictionary<string, string> in MyClass. The only members that actually need to be implemented are the enumerator. There you would return the content of the dictionary, as well as another entry for each additional property.

If you prefer to keep your POCO clean, you could create a class that implements IYamlTypeConverter. I don't have a PC at hand to implement it for you, but you could use the this code as an example:

https://dotnetfiddle.net/1plIcc

(Sorry, copying the code here is not working on a smart phone. I will add the code when when I have access to a proper PC)

Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74
  • Thanks Antoine. I got it working with the IDictionary<> approach but tried implementing IYamlConverter and iterating the Dictionary there but it was still outputting the 'Bar' key each time (unless I'm missing something!) – Fermin Jun 30 '16 at 06:59