How do I create recursive custom tags in YAMLDotNet

Viewed 82

I'm working with YAML in C#, using YamlDotNet. I've created a custom tag that will deserialize to a simple object supporting string interpolation. Let's say the tag is "!StrInterp", and its structure is a template string and a sequence of args to interpolate. In the YAML it looks something like this:

Blah: !StrInterp
  Template: "My {0} says {1}"
  Args: ["dog", "woof"]

That YAML structure maps to a simple C# class like this:

public class StrInterp
{
    public string Template { get; set; }
    public IList<string> Args { get; set; }
}

Got this working by adding a simple tag mapping to the deserializer, like this:

var deserializer = new DeserializerBuilder()
  .WithTagMapping("!StrInterp", typeof(StrInterp)
  .Build()

So far so good.

What I want to do is extend that so that the args can themselves be !StrInterp tags, e.g.:

Blah: !Str
  Template: "My {0} says {1}"
  Args: ["dog", !Str { Template: "{0} and {1}", Args: ["woof", "arf"] }]

It seems like I need some kind of variant type for the Args list, so that an arg could be either an !Str tag or a simple scalar string, but I'm not aware of any such type in C#.

Is there a way to do this? Thank you!

0 Answers
Related