2

在 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")),您将在序列中获得一个“空”条目,但如果您将序列化留给 YamlDotNet,它将被序列化为“”(空字符串)。

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

4

2 回答 2

2

实现此目的的一种方法是创建一个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();

这是这段代码的小提琴

于 2017-10-26T09:22:07.123 回答
0

根据http://www.yaml.org/refcard.html ,您似乎可以简单地用'〜'表示一个空值

于 2017-10-24T14:31:11.117 回答