Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Created July 31, 2024 06:27
Show Gist options
  • Save vurdalakov/605ba28ba4063e37ab4aedab7e320e93 to your computer and use it in GitHub Desktop.
Save vurdalakov/605ba28ba4063e37ab4aedab7e320e93 to your computer and use it in GitHub Desktop.
String array converter for YamlDotNet
namespace Vurdalakov.YamlDotNetStringArrayConverter
{
using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
internal class Program
{
static void Main(String[] args)
{
var yaml = "title: My page\r\ntags: tag1;tag2;tag3";
var yamlDeserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.WithTypeConverter(new StringArrayConverter())
.Build();
var metadata = yamlDeserializer.Deserialize<Metadata>(yaml);
Console.WriteLine($"Title='{metadata.Title}'");
foreach (var tag in metadata.Tags)
{
Console.WriteLine($"Tag='{tag}'");
}
}
}
public class Metadata
{
public String Title { get; set; }
[YamlConverter(typeof(StringArrayConverter))]
public String[] Tags { get; set; }
}
public class StringArrayConverter : IYamlTypeConverter
{
private readonly Char _separator;
public StringArrayConverter(Char separator = ';') => this._separator = separator;
public Boolean Accepts(Type type) => typeof(String[]) == type;
public Object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
var value = parser.Consume<Scalar>().Value;
return value.Split(this._separator);
}
public void WriteYaml(IEmitter emitter, Object value, Type type, ObjectSerializer serializer)
{
var array = value as String[];
emitter.Emit(new Scalar(AnchorName.Empty, TagName.Empty, String.Join(this._separator, array), ScalarStyle.Any, true, false));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment