在 YamlDotNet 中:有没有办法将空值输出为序列中的空字符串?

In YamlDotNet: Is there a way to output a null value as an empty string in a sequence?

在 IYamlTypeConverter 中编写序列时,您可能会使用如下代码:

public class MyObjectConverter : IYamlTypeConverter {
    public MyObjectConverter() {}

    public bool Accepts(Type type) { return typeof(IMyObject) == type || typeof(IMyObject[]) == type; }
    public object ReadYaml(IParser parser, Type type) { return null; }
    public void WriteYaml(IEmitter emitter, object value, Type type) {
        var itemVal = value as IMyObject;
        if (itemVal != null)
            emitter.Emit(new Scalar(itemVal.GetID()));
        else {
            var arrayVal = value as IMyObject[];
            emitter.Emit(new SequenceStart(null, null, true, SequenceStyle.Block));
            if (arrayVal != null) {
                foreach (var item in arrayVal)
                    if (item != null) emitter.Emit(new Scalar(item.GetID()));
                    else              emitter.Emit(new Scalar("null"));
            }
            emitter.Emit(new SequenceEnd());
        }
    }
}

通过调用 emitter.Emit(new Scalar("null")),您将在序列中获得一个 'null' 条目,但是如果您将序列化留给 YamlDotNet,它将被序列化为 ''(空字符串)。

如何在编写自定义 IYamlTypeConverter 时将序列中的空值输出为空字符串?

根据 http://www.yaml.org/refcard.html

,您似乎可以简单地用 '~' 表示空值

实现此目的的一种方法是创建自定义 IEventEmitter 以添加此逻辑:

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

    public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
    {
        if (eventInfo.Source.Type == typeof(string) && eventInfo.Source.Value == null)
        {
            emitter.Emit(new Scalar(string.Empty));
        }
        else
        {
            base.Emit(eventInfo, emitter);
        }
    }
}

然后你这样注册:

var serializer = new SerializerBuilder()
    .WithEventEmitter(nextEmitter => new NullStringsAsEmptyEventEmitter(nextEmitter))
    .Build();

Here's a fiddle with this code