You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为List<string>中的字符串应用YamlDotNet的ScalarStyle.SingleQuoted?

解决方案

[YamlMember]特性仅作用于属性本身,无法控制集合内的元素样式,可通过以下两种方式实现需求:

方案1:针对特定字符串集合配置(推荐,不影响其他字符串序列化逻辑)

  1. 自定义集合类型转换器,指定集合内字符串统一使用单引号:
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

public class SingleQuotedStringListConverter : IYamlTypeConverter
{
    public bool Accepts(Type type)
    {
        return type == typeof(List<string>);
    }

    public object? ReadYaml(IParser parser, Type type)
    {
        // 如需反序列化可自行实现对应逻辑
        throw new NotImplementedException();
    }

    public void WriteYaml(IEmitter emitter, object? value, Type type)
    {
        var list = value as List<string>;
        if (list == null) return;

        emitter.Emit(new SequenceStart(AnchorName.Empty, TagName.Empty, isImplicit: true, SequenceStyle.Block));
        foreach (var item in list)
        {
            emitter.Emit(new Scalar(AnchorName.Empty, TagName.Empty, item, ScalarStyle.SingleQuoted, isPlainImplicit: true, isQuotedImplicit: false));
        }
        emitter.Emit(new SequenceEnd());
    }
}
  1. 给目标集合属性添加转换器标记:
public class Thing
{
    [YamlMember(ScalarStyle = ScalarStyle.SingleQuoted)]
    public string Name;

    // 替换原有的YamlMember特性,添加转换器标记
    [YamlConverter(typeof(SingleQuotedStringListConverter))]
    public List<string> Attributes;
}

修改后直接用原有逻辑序列化即可得到预期输出。

方案2:全局配置所有字符串使用单引号

如果业务要求所有字符串序列化时都加单引号,可以用自定义值序列化器全局配置:

  1. 实现自定义值序列化器:
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

public class SingleQuotedStringSerializer : IValueSerializer
{
    private readonly IValueSerializer _innerSerializer;

    public SingleQuotedStringSerializer(IValueSerializer innerSerializer)
    {
        _innerSerializer = innerSerializer;
    }

    public void SerializeValue(IEmitter emitter, object? value, Type? type)
    {
        if (value is string str)
        {
            emitter.Emit(new Scalar(AnchorName.Empty, TagName.Empty, str, ScalarStyle.SingleQuoted, true, false));
            return;
        }
        _innerSerializer.SerializeValue(emitter, value, type);
    }
}
  1. 构建序列化器时注入自定义序列化逻辑:
var ymlSerializer = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitEmptyCollections | DefaultValuesHandling.OmitNull)
    // 注入自定义字符串序列化逻辑
    .WithValueSerializer((inner, _) => new SingleQuotedStringSerializer(inner))
    .Build();

该方案无需修改原有属性标记,所有字符串属性、集合内的字符串元素都会自动用单引号包裹。


内容的提问来源于stack exchange,提问作者Zee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:15:08