using System.IO; using System.Threading.Tasks; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; namespace ColdMint.scripts.serialization; public static class YamlSerialization { /// /// YamlDeserializer /// Yaml反序列化器 /// private static readonly IDeserializer YamlDeserializer = new DeserializerBuilder() .WithNamingConvention(UnderscoredNamingConvention.Instance) // convent snake_case .Build(); private static readonly ISerializer YamlSerializer = new SerializerBuilder() .WithNamingConvention(UnderscoredNamingConvention.Instance) // convent snake_case .Build(); /// /// Read a Json file to type T /// 读取一个Json文件到T类型 /// /// /// /// public static async Task ReadYamlFileToObj(string path) { await using var openStream = File.OpenRead(path); var yaml = await new StreamReader(openStream).ReadToEndAsync(); return YamlDeserializer.Deserialize(yaml); } /// /// Serialize the object to Json /// 将对象序列化为Yaml /// /// /// public static string Serialize(object obj) { return YamlSerializer.Serialize(obj); } /// /// Deserialize Yaml to the object /// 反序列化Yaml到对象 /// /// /// /// public static T Deserialize(string yaml) { return YamlDeserializer.Deserialize(yaml); } }