Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to serialize into a specific format

Using YamlDotNet, how to serialize a byte[] like that [49,20,50]?

The yaml file I need is:

    device:
      name: device1
      key: [49,20,50]

I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Defined the key as byte[], however, the yaml looks like it:
    device:
      name: device1
      key: 
        - 49
        - 20
        - 50
  • Defined the key as string and create an IYamlTypeConverter that is using $"[ {string.Join(",", bytes.ToArray())} ]" to convert it, however, the key is created between single quote
    '. The yaml looks like it:
    device:
      name: device1
      key: '[49,20,50]'

My model is:

    public class device
    {
       public string name{ get; set; }
       public string key{ get; set; } OR public byte[] key{ get; set; } 
    }

Thanks

>Solution :

What you want is called "FlowStyle" and the docs describe how to get it:

YamlDotNet Documentation

Disclaimer: All following examples are 1:1 copies from above linked documentation! (Copied here to avoid "link-only" answer / avoid dead link)

The example is for integer sequences. You need to declare an event emitter:

class FlowStyleIntegerSequences : ChainedEventEmitter
{
    public FlowStyleIntegerSequences(IEventEmitter nextEmitter)
        : base(nextEmitter) {}

    public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter)
    {
        if (typeof(IEnumerable<int>).IsAssignableFrom(eventInfo.Source.Type))
        {
            eventInfo = new SequenceStartEventInfo(eventInfo.Source)
            {
                Style = SequenceStyle.Flow
            };
        }

        nextEmitter.Emit(eventInfo, emitter);
    }
}

and then use it:

var serializer = new SerializerBuilder()
    .WithEventEmitter(next => new FlowStyleIntegerSequences(next))
    .Build();

serializer.Serialize(Console.Out, new {
    strings = new[] { "one", "two", "three" },
    ints = new[] { 1, 2, 3 }
});

produces

strings:
- one
- two
- three
ints: [1, 2, 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading