首页 > Windows开发 > 详细

在 .NET 中使用 C# 处理 YAML

时间:2021-02-04 21:01:16      阅读:42      评论:0      收藏:0      [点我收藏+]

技术分享图片

在 .NET 中,可以使用 YamlDotNet 类库解析和生成 YAML 文件。

YamlDotNet : https://github.com/aaubry/YamlDotNet

NuGet 下载:https://www.nuget.org/packages/YamlDotNet/

帮助文档:https://github.com/aaubry/YamlDotNet/wiki

序列化一个对象为 YAML 格式

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...

 var person = new Person
{
    Name = "Abe Lincoln",
    Age = 25,
    HeightInInches = 6f + 4f / 12f,
    Addresses = new Dictionary<string, Address>{
        { "home", new  Address() {
                Street = "2720  Sundown Lane",
                City = "Kentucketsville",
                State = "Calousiyorkida",
                Zip = "99978",
            }},
        { "work", new  Address() {
                Street = "1600 Pennsylvania Avenue NW",
                City = "Washington",
                State = "District of Columbia",
                Zip = "20500",
            }},
    }
};

var serializer = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();
var yaml = serializer.Serialize(person);
System.Console.WriteLine(yaml);
// Output: 
// name: Abe Lincoln
// age: 25
// heightInInches: 6.3333334922790527
// addresses:
//   home:
//     street: 2720  Sundown Lane
//     city: Kentucketsville
//     state: Calousiyorkida
//     zip: 99978
//   work:
//     street: 1600 Pennsylvania Avenue NW
//     city: Washington
//     state: District of Columbia
//     zip: 20500

反序列化 YAML 到对象

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...

var yml = @"
name: George Washington
age: 89
height_in_inches: 5.75
addresses:
  home:
    street: 400 Mockingbird Lane
    city: Louaryland
    state: Hawidaho
    zip: 99970
";

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)  // see height_in_inches in sample yml 
    .Build();

//yml contains a string containing your YAML
var p = deserializer.Deserialize<Person>(yml);
var h = p.Addresses["home"];
System.Console.WriteLine($"{p.Name} is {p.Age} years old and lives at {h.Street} in {h.City}, {h.State}.");
// Output:
// George Washington is 89 years old and lives at 400 Mockingbird Lane in Louaryland, Hawidaho.

转换 YAML 为 JSON 格式

var r = new StringReader(@"
scalar: a scalar
sequence:
  - one
  - two
");
var deserializer = new DeserializerBuilder().Build();
var yamlObject = deserializer.Deserialize(r);

var serializer = new SerializerBuilder()
	.JsonCompatible()
	.Build();

var json = serializer.Serialize(yamlObject);

Console.WriteLine(json);

该代码会产生以下输出:

{"scalar": "a scalar", "sequence": ["one", "two"]}

 

在 .NET 中使用 C# 处理 YAML

原文:https://www.cnblogs.com/Soar1991/p/14374156.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!