C# Yaml 使用示範

安裝

先使用 NuGet 安裝 YamlDotNet 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package YamlDotNet
    

序列化(Serialization)

範例物件:
    
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
    public List<string> Phones { get; set; }
}
    

序列化:
    
User user = new()
{
    Id = 1,
    Name = "Ruyut",
    Email = "a@ruyut.com",
    Age = 100,
    Phones = new()
    {
        "123456789",
        "987654321"
    }
};

var serializerBuilder = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

Console.WriteLine(serializerBuilder.Serialize(user));
    

輸出範例:
    
id: 1
name: Ruyut
email: a@ruyut.com
age: 100
phones:
- 123456789
- 987654321
    

WithNamingConvention 是用於將屬性轉換為 yaml 時的命名方式,可用選項如下:
  • CamelCaseNamingConvention.Instance 例: userName:
  • PascalCaseNamingConvention.Instance 例: UserName
  • LowerCaseNamingConvention.Instance 例: username
  • UnderscoredNamingConvention.Instance 例: user_name
  • HyphenatedNamingConvention.Instance 例: user-name

反序列化(Deserialization)

    
string yaml = """
id: 1
name: Ruyut
email: a@ruyut.com
age: 100
phones:
- 123456789
- 987654321
""";

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)
    .Build();

var user = deserializer.Deserialize<User>(yaml);
    

忽略無效屬性

如果有屬性無法對應,會出現下列錯誤:

Property 'Address' not found on type 'User'.
    

可以加上 IgnoreUnmatchedProperties 來使其忽略
    
var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)
    .IgnoreUnmatchedProperties()
    .Build();
    

其他屬性

自訂屬性名稱

Id 在輸出時會顯示為 UserId
    
public class User
{
    [YamlMember(Alias = "UserId")]
    public int Id { get; set; }
}
    

忽略屬性

Age 屬性並不會被輸出
    
public class User
{
    [YamlIgnore]
    public int Age { get; set; }
}
    

輸出註解

有些屬性名稱並沒有辦法很好的表達完整的意思,這時候可以使用 YamlMemberAttribute 的 Description 屬性,在序列化為 yaml 時會自動以註解的方式輸出說明
    
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    [YamlMember(Description = "年齡")]
    public int Age { get; set; }
}
    

輸出範例:
    
id: 1
name: Ruyut
# 年齡
age: 100
    



參考資料:
NuGet - YamlDotNet
Github - aaubry/YamlDotNet

留言