LoginSignup
17
19

More than 5 years have passed since last update.

.NET上でyamlファイルをデシリアライズしたくなったときはYamlDotNetを!

Posted at

概要

.NET上でyamlファイルを読み込んでいい感じに使いたくなったので調べてみました。サンプルコードを参考にしたサイト・記事をまとめます。

準備

  • NuGetでYamlDotNet(この記事を書いた時点ではver.3.8.0)をインストールします。
  • YamlファイルはC:\Users\[UserName]\Documents\Visual Studio 2015\Projects\YamlSample\YamlSample\bin\Debug下に置いて試しました。

サンプル

YamlSample.cs

using System;
using System.Text;
using System.IO;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using System.Collections.Generic;


namespace YamlSample
{
    class Program
    {
        static void Main(string[] args)
        {
                        // YAMLのストリームを解析して読み込むとき
            var input = new StreamReader(@"cshp.yaml", Encoding.UTF8);
            var yaml = new YamlStream();
            yaml.Load(input);
            var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
            var date = (YamlScalarNode)mapping.Children[new YamlScalarNode("date")];
            Console.WriteLine("date\t{0}", date.Value);
            // 2015-5-28-01
            var thema = (YamlScalarNode)mapping.Children[new YamlScalarNode("thema")];
            Console.WriteLine("thema\t{0}", thema.Value);
            // C# Tips
            Console.WriteLine("hoepages:");
            var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("homepage:")];
            foreach (YamlMappingNode item in items)
            {
                foreach (var child in item)
                {
                    Console.WriteLine(
                        "{0}\t{1}",
                        ((YamlScalarNode)child.Key).Value,
                        ((YamlScalarNode)child.Value).Value);
                }
                // homepage:
                // title   .NET Tips
                // url     http://dobon.net/vb/dotnet/index.html
                // title   .NETプログラミングにピンポイントで役立つテクニックとヒント集
                // url     http://www.atmarkit.co.jp/ait/subtop/features/dotnet/dotnettips_index.html
                // title   初めてのC#
                // url     http://homepage3.nifty.com/midori_no_bike/CS/
            }
            input.Close();



                        // C#のクラスにデシリアライズして読み込むとき
            DeserializedObject obj = YamlImporter.Deserialize("cshp.yaml");
            Console.WriteLine(obj.homepages);
            // System.Collections.Generic.List`1[YamlSample.Program+DesirializedObject+HomePage]
            Console.WriteLine(obj.thema);
            // C# Tips
            Console.WriteLine(DateTime.Parse(obj.date));
            // 2015/05/28 10:00:00
            Console.WriteLine(obj.homepages[0].title);
            // .NET Tips
        }

        public class DeserializedObject
        {
            public string date { get; set; }

            public string thema { get; set; }

            [YamlMember(Alias = "homepage")]
            public List<HomePage> homepages { get; set; }

            public class HomePage
            {
                public string title { get; set; }
                public string url { get; set; }
            }
        }

        public class YamlImporter
        {
            public static DeserializedObject Deserialize(string yamlName)
            {
                StreamReader sr = new StreamReader(yamlName);
                string text = sr.ReadToEnd();
                var input = new StringReader(text);
                var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
                DeserializedObject deserializeObject = deserializer.Deserialize<DeserializedObject>(input);
                return deserializeObject;
            }
        }
    }
}
cshp.yaml

date: 2015-5-28-01
thema: C# Tips
homepage:
    - title: ".NET Tips"
      url: http://dobon.net/vb/dotnet/index.html
    - title: ".NETプログラミングにピンポイントで役立つテクニックとヒント集"
      url: http://www.atmarkit.co.jp/ait/subtop/features/dotnet/dotnettips_index.html
    - title: "初めてのC#"
      url: http://homepage3.nifty.com/midori_no_bike/CS/
...

参考

YAMLにあるキーの左隣の空白が半角スペース12個、インデントは半角スペース4個になっていないとデシリアライズに失敗する

これについてはYamlDotNetの3.8.0では解消しているようです!

17
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
19