如何序列化为特定格式

问题描述 投票:0回答:1

使用 YamlDotNet,如何序列化这样的

byte[]
[49,20,50]

我需要的yaml文件是:

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

我已经尝试过:

  • 将键定义为
    byte[]
    ,但是 yaml 看起来像这样:
    device:
      name: device1
      key: 
        - 49
        - 20
        - 50
  • 将键定义为
    string
    并创建一个使用
    IYamlTypeConverter
    进行转换的
    $"[ {string.Join(",", bytes.ToArray())} ]"
    ,但是,键是在单引号之间创建的
    '
    。 yaml 看起来像这样:
    device:
      name: device1
      key: '[49,20,50]'

我的型号是:

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

谢谢

c# serialization yaml yamldotnet
1个回答
0
投票

您想要的称为“FlowStyle”,文档描述了如何获取它:

YamlDotNet 文档

免责声明:以下所有示例均来自上述链接文档的 1:1 副本! (复制到这里以避免“仅链接”答案/避免死链接)

该示例适用于整数序列。您需要声明一个事件发射器:

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);
    }
}

然后使用它:

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 }
});

产生

strings:
- one
- two
- three
ints: [1, 2, 3]
© www.soinside.com 2019 - 2024. All rights reserved.