(C#)JSON, XML

業務でC#を使うことになった。
4/1からの現場だったが新型コロナの緊急事態宣言により自宅待機となり勉強中。
C#はじめてなのでこの時間はありがたい。

っと、その前に自宅待機を選択してくれた出向先には感謝しかない。
復帰後には良いシステムを構築してお返ししたいと思う。

ということ、業務に向けて。


JSON/XMLの操作について調べました。
手持ちの書籍(2017年版)でXMLの操作がとても難しく書いてあって「本当にここまでするの?」と感じてググってみると簡単な方法あった。
書籍は体系的に学べるのはよいものの、情報が古くなってしまうとかなりツライものがあります。

凄まじく簡単で驚いた。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text.Json;
using Microsoft.VisualBasic.FileIO;
namespace XmlJsonCsv
{
    class Program
    {
        public const string FileName = @"C:\Users\masawa\Documents\test";

        static void Main(string[] args)
        {
            Console.WriteLine("-----[XML]-----");
            new XML().Execute();

            Console.WriteLine("-----[JSON]-----");
            new JSON().Execute();
        }
    }

    class XML
    {
        public void Execute()
        {
            string fileName = Program.FileName + ".xml";

            var root = new Root(Author.Authors());

            using (var writer = new StreamWriter(fileName))
            {
                var serializer = new XmlSerializer(typeof(Root));
                serializer.Serialize(writer, root);
            }

            using (var reader = new StreamReader(fileName))
            {
                var serializer = new XmlSerializer(typeof(Root));
                Root deserializedRoot = (Root)serializer.Deserialize(reader);

                List<Author> authors = deserializedRoot.Authors;
                authors.ForEach(a => Console.WriteLine(a.ToString()));
            }
        }
    }

    class JSON
    {
        public void Execute()
        {
            var root = new Root(Author.Authors());

            string jsonText = JsonSerializer.Serialize(root, typeof(Root));
            Console.WriteLine("JSON Text: {0}", jsonText);

            var deserializedRoot = JsonSerializer.Deserialize<Root>(jsonText);

            List<Author> authors = deserializedRoot.Authors;
            authors.ForEach(a => Console.WriteLine(a.ToString()));

        }
    }

    public class Book
    {
        public string Title { get; set; }
        public int Price { get; set; }

        public Book() { }

        public Book(string title, int price)
        {
            this.Title = title;
            this.Price = price;
        }

        public override string ToString()
        {
            return String.Format("Book({0}, {1})", this.Title, this.Price);
        }

        public static List<Book> Books()
        {
            var books = new List<Book>
            {
                new Book("Book 1", 100),
                new Book("Book 2", 200),
                new Book("Book 3", 300),
            };
            return books;
        }
    }

    [XmlRoot("root")]
    public class Root
    {
        [XmlArray("authors")]
        [XmlArrayItem("author")]
        public List<Author> Authors { get; set; }

        public Root() { }

        public Root(List<Author> authors)
        {
            this.Authors = authors;
        }
    }

    public class Author
    {
        [XmlElement(ElementName = "name")]
        public string Name { get; set; }

        [XmlElement(ElementName = "books")]
        public List<Book> Books { get; set; }

        public Author() { }

        public Author(string name, List<Book> books)
        {
            this.Name = name;
            this.Books = books;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            this.Books.ForEach(b => sb.Append(b.ToString() + ", "));
            string books = sb.ToString();

            return String.Format("Author({0}, {1})", this.Name, books.Substring(0, books.Length - 2));
        }

        public static List<Author> Authors()
        {
            var authors = new List<Author> {
                new Author("Author 1", Book.Books()),
                new Author("Author 2", Book.Books()),
                new Author("Author 3", Book.Books()),
            };
            return authors;
        }
    }
}

凄まじく簡単だ。