LoginSignup
0
1

More than 1 year has passed since last update.

C# シリアライズ方法 JSONSerializer

Posted at
using System.Text.Json;

// 適当なデータ(クラスオブジェクトのリスト)
public class C{
  public int id {get;set;}  // プロパティでないと認識しなかった
  public int val {get;set;}
}
var lis = new List<C>(){
  new C(1,11),
  new C(2,22)
};

// シリアライズ
var json = JsonSerializer.Serialize(lis);
// 第二引数にオプションもある 改行付与など
//  ,new JsonSerializerOptions{WriteIndented = true}

// 例えばファイルに書き込み
File.WriteAllText("test.json", json);
// 読込
var jsonText = File.ReadAllText("test.json");

// デシリアライズ <受けとる型>
var lis2 = JsonSerializer.Deserialize<List<C>>(jsonText); 
foreach(var v in lis2){
    Console.WriteLine($"{v.id},{v.val}");
}

以上

0
1
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
1