我正在使用YamlDotNet来序列化像这样的对象
using System.Collections.Generic;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
public class Thing
{
[YamlMember(ScalarStyle = ScalarStyle.SingleQuoted)]
public string Name
[YamlMember(ScalarStyle = ScalarStyle.SingleQuoted)]
public List<string> Attributes
}
我正在按预期成功地序列化纯字符串属性
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
var myObject = new Thing
{
Name = "foo"
Attributes = new List<string>() { "bar" }
};
var ymlSerializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitEmptyCollections | DefaultValuesHandling.OmitNull)
.Build();
var serializedYaml = ymlSerializer.Serialize(myObject);
生产yaml:
name: 'foo'
attributes:
- bar
预期yaml:
name: 'foo'
attributes:
- 'bar'
如何将标量样式属性应用于基元的列表?
您必须使用自定义转换器:
自定义类转换器:
public class ThingCategoryYamlTypeConverter : IYamlTypeConverter
{
private void WriteContentCategory(IEmitter emitter, object value)
{
Thing node;
node = (Thing)value;
emitter.Emit(new MappingStart(null, null, false, MappingStyle.Block));
if (node.Name != null)
{
emitter.Emit(new Scalar(null, "name"));
emitter.Emit(new Scalar(null, null, node.Name, ScalarStyle.SingleQuoted, true, false));
}
if (node.Attributes != null)
{
this.WriteAttributes(emitter, node);
}
emitter.Emit(new MappingEnd());
}
private void WriteAttributes(IEmitter emitter, Thing node)
{
emitter.Emit(new Scalar(null, "attributes"));
emitter.Emit(new SequenceStart(null, null, false, SequenceStyle.Block));
foreach (string child in node.Attributes)
{
emitter.Emit(new Scalar(null, null, child, ScalarStyle.SingleQuoted, true, false ));
}
emitter.Emit(new SequenceEnd());
}
public bool Accepts(Type type)
{
return type == typeof(Thing);
}
public object ReadYaml(IParser parser, Type type)
{
// use for deserialization
throw new NotImplementedException();
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
this.WriteContentCategory(emitter, value);
}
}
你的班级:
public class Thing
{
public string Name;
public List<string> Attributes;
}
调用自定义转换器
static void Main(string[] args)
{
var myObject = new Thing
{
Name = "foo",
Attributes = new List<string> { "bar" }
};
var ymlSerializer = new SerializerBuilder()
.WithTypeConverter(new ThingCategoryYamlTypeConverter())
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitEmptyCollections | DefaultValuesHandling.OmitNull)
.Build();
var serializedYaml = ymlSerializer.Serialize(myObject);
}
结果:
name: 'foo'
attributes:
- 'bar'