gpt4 book ai didi

yamldotnet - 如何在 Yamldotnet 中跳过空集合

转载 作者:行者123 更新时间:2023-12-04 01:43:33 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用 YamlDotNet 跳过序列化空集合。我对自定义 ChainedObjectGraphVisitorIYamlTypeConverter 进行了试验。我是使用 YamlDotNet 的新手,这里有一些知识空白。

下面是我对访问者模式的实现,它导致了 YamlDotNet.Core.YamlException "Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got MappingEnd" 错误。我确实看到了一些关于 MappingStart/MappingEnd 的在线内容,但我不确定它如何适合我正在尝试做的事情(消除大量空集合中的困惑)。任何指向正确方向的指示都将受到赞赏。

实例化序列化器:

var serializer = new YamlDotNet.Serialization.SerializerBuilder()
.WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention())
.WithEmissionPhaseObjectGraphVisitor(args => new YamlIEnumerableSkipEmptyObjectGraphVisitor(args.InnerVisitor))
.Build();

ChainedObjectGraphVisitor 实现:

    public sealed class YamlIEnumerableSkipEmptyObjectGraphVisitor : ChainedObjectGraphVisitor
{
public YamlIEnumerableSkipEmptyObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor)
: base(nextVisitor)
{
}

public override bool Enter(IObjectDescriptor value, IEmitter context)
{
bool retVal;

if (typeof(System.Collections.IEnumerable).IsAssignableFrom(value.Value.GetType()))
{ // We have a collection
var enumerableObject = (System.Collections.IEnumerable)value.Value;
if (enumerableObject.GetEnumerator().MoveNext()) // Returns true if the collection is not empty.
{ // Serialize it as normal.
retVal = base.Enter(value, context);
}
else
{ // Skip this item.
retVal = false;
}
}
else
{ // Not a collection, normal serialization.
retVal = base.Enter(value, context);
}

return retVal;
}
}

最佳答案

我相信答案也是用与在 Enter() 方法中所做的类似的逻辑覆盖基类中的 EnterMapping() 方法:

public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context)
{
bool retVal = false;

if (value.Value == null)
return retVal;

if (typeof(System.Collections.IEnumerable).IsAssignableFrom(value.Value.GetType()))
{ // We have a collection
var enumerableObject = (System.Collections.IEnumerable)value.Value;
if (enumerableObject.GetEnumerator().MoveNext()) // Returns true if the collection is not empty.
{ // Don't skip this item - serialize it as normal.
retVal = base.EnterMapping(key, value, context);
}
// Else we have an empty collection and the initialized return value of false is correct.
}
else
{ // Not a collection, normal serialization.
retVal = base.EnterMapping(key, value, context);
}

return retVal;
}

关于yamldotnet - 如何在 Yamldotnet 中跳过空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56411304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com