YamlDotNet
YamlDotNet copied to clipboard
KeyValue Comments
Hi,
I'm using your library to generate my I18n translations right here : https://github.com/NosWings/NosWings.Server.Translations
I got a Dictionary, with an enum as a key and a string as value (for my i18n) here is an example project I'd like to make working https://dotnetfiddle.net/XS8DBo
Is it possible to have a Type converter that will append a comment after the KeyPairValue's value
I tried to simply make a type converter for my Enum, but it does not work, it simply breaks the YAML cause it's appended after the Key
Expected :
BlaBlaBla: '{0}' # Params : {0} FirstParamName
BlaBla2: '{0} {1}' # Params: {0} FirstParamName, {1} SecondParamName
Result with only my enum TypeConverter :
BLABLABLA
# Params : {0} : FirstParamName
: '{0}'
BLABLA2
# Params : {0} : FirstParamName, {1} : SecondParamName
: '{0} {1}'
My BrokenEnumTypeConverter
public class I18nKeyTypeConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(I18nKey);
public object? ReadYaml(IParser parser, Type type)
{
string value = parser.Consume<Scalar>().Value;
Enum.TryParse(value, out I18nKey key);
return key;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var key = (I18nKey)value;
emitter.Emit(new Scalar(null, null, key.ToString().ToUpper()));
if (!(typeof(I18nKey).GetField(key.ToString()).GetCustomAttribute(typeof(I18NParamsAttribute)) is I18NParamsAttribute tmp))
{
return;
}
emitter.Emit(new Comment(PrettifyI18NParams(tmp), false));
}
}
Thanks by advance.
You are emitting the comment after the key, that's why it gets in between the key and the : indicator. You would need to have a converter to the value instead of the key, or perhaps a converter for the dictionary would be simpler.