LoginSignup
0
0

More than 3 years have passed since last update.

C# 勉強 JSONシリアル化

Last updated at Posted at 2020-05-26
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace List1231{
    class Program{
        static void Main(string[] args){

            var novels = new Novel[] {
              new Novel {
                Author = "吉川英治",
                Title = "宮本武蔵",
                Published = 1939,
              },
              new Novel {
                Author = "吉川英治",
                Title = "三国志",
                Published = 1940,
              },
            };
            using (var stream = new FileStream("novels.json", FileMode.Create,
                                                FileAccess.Write)) {
                var serializer = new DataContractJsonSerializer(novels.GetType());
                serializer.WriteObject(stream, novels);
            }

            var lines = File.ReadLines("novels.json");
            foreach (var line in lines)
                Console.WriteLine(line);

        }
    }
}

クラス

Novel.cs

using System.Runtime.Serialization;

namespace List1231{
    [DataContract(Name="novel")]
    public class Novel{
        [DataMember(Name="title")]
        public string Title {get;set;}

        [DataMember(Name="author")]
        public string Author {get;set;}

        [DataMember(Name="published")]
        public int Published {get;set;}

        public override string ToString(){
            return string.Format("Title={0},Author={1},Published=[2]",
                Title,Author,Published);
        }
    }
}
0
0
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
0
0