YamlDotNet and custom types

I am opening yaml and yamldotnet. Sorry if this is a fairly simple question:

  • Does it make sense to define custom types in yaml using a single exclamation mark, for example:

    red:! color {red: 255, green: 0, blue: 0}

  • How is this deserialized YamlDotNet? In other words, is there a way to ensure that the type's color is mapped to the corresponding Color type in .net?

  • From my understanding of the following example https://dotnetfiddle.net/HD2JXM , YamlDotNet uses an implicit mapping between the yaml document and the .net class to map yaml properties to the corresponding class properties (as shown in the example, this can be customized using annotations). However, no type checking is performed.

Clarify the situation. I have the following yaml document that corresponds to a set of widgets:

controls:
  - Button:
      id: 1
      text: Hello Button World
  - Label:
      id: 2
      text: Hello Label World
  - TextView:
      id: 3
      content: >
        This is some sample text that will appear
        in a text view.

      

And I want to map it to the corresponding type hierarchy in C #:

class AOPage
{
    public IList<AOControl> Controls { get; set; }

}

class AOControl 
{
    public int Id { get; set;}
}

class AOLabel : AOControl
{
    public String Text { get; set;}
}

class AOButton : AOControl
{
    public String Text { get; set;}
}

class AOTextView : AOControl
{
    public String Contents{ get; set;}
}

      

Note that there is a similar question here: Using a custom type resolver , which has not been answered.

Thank!

+3


source to share


1 answer


If you omit the tag, the deserializer uses the type information from the object graph that is being deserialized.

To do what you want with YamlDotNet, the easiest way is to use a local tag, say !!color

, and then register a tag mapping for that tag:



deserializer.RegisterTagMapping("tag:yaml.org,2002:color", typeof(Color));

      

You can see a working example at DeserializeCustomTags unit test .

0


source







All Articles