Search code examples
c#serializationyamlyamldotnet

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:

  • 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]