4
0

NotesStringYamlConverter.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using YamlDotNet.Core;
  2. using YamlDotNet.Core.Events;
  3. using YamlDotNet.Serialization;
  4. public sealed class NotesStringYamlConverter : IYamlTypeConverter
  5. {
  6. public bool Accepts(Type type) => type == typeof(string);
  7. public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
  8. {
  9. var scalar = parser.Consume<Scalar>();
  10. return scalar.Value;
  11. }
  12. public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
  13. {
  14. if (value is null)
  15. {
  16. emitter.Emit(new Scalar(
  17. AnchorName.Empty,
  18. TagName.Empty,
  19. "",
  20. ScalarStyle.Plain,
  21. true,
  22. true));
  23. return;
  24. }
  25. var s = (string)value;
  26. if (s.Contains('\n'))
  27. {
  28. // Literal block style (|)
  29. emitter.Emit(new Scalar(
  30. AnchorName.Empty,
  31. TagName.Empty,
  32. s,
  33. ScalarStyle.Literal,
  34. true,
  35. false));
  36. }
  37. else
  38. {
  39. emitter.Emit(new Scalar(s));
  40. }
  41. }
  42. }