LoginSignup
3
6

More than 5 years have passed since last update.

C#メモ JSON読み書き

Last updated at Posted at 2017-02-18

コード

// "System" と "System.Collections.Generic" をusing
// "System.Web.Extensions" を参照設定
var js = new System.Web.Script.Serialization.JavaScriptSerializer();

// シリアライズ
var p = new Person();
p.Age = 80;
p.Name = "太郎";
string jsonString1 = js.Serialize(p);
Console.WriteLine($"シリアライズ結果1:{jsonString1}");

// デシリアライズ
Person p2 = js.Deserialize<Person>(jsonString1);

// シリアライズ(複数)
var persons = new List<Person>();
persons.Add(new Person { Name = "次郎", Age = 75 });
persons.Add(new Person { Name = "三郎", Age = 60 });
string jsonString2 = js.Serialize(persons);
Console.WriteLine($"シリアライズ結果2:{jsonString2}");

// デシリアライズ(複数)
List<Person> persons2 = js.Deserialize<List<Person>>(jsonString2);
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

実行結果

シリアライズ結果1:{"Name":"太郎","Age":80}
シリアライズ結果2:[{"Name":"次郎","Age":75},{"Name":"三郎","Age":60}]

参考サイト

3
6
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
3
6