1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

firesignAdvent Calendar 2023

Day 25

C# Newtonsoft.Jsonを使用してJsonファイルを扱う

Posted at

はじめに

Newtonsoft.Jsonを使用して、JsonファイルのSave/Loadをする。

インストール

コンソールでのパッケージ追加
Install-Package Newtonsoft.Json

コード

サンプルのデータモデル
class DataModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}
JsonファイルのSave/Load

static void SaveToJsonFile<T>(T data, string filePath)
{
    string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
    File.WriteAllText(filePath, jsonData);
}

static T LoadFromJsonFile<T>(string filePath)
{
    if (File.Exists(filePath))
    {
        string jsonData = File.ReadAllText(filePath);
        return JsonConvert.DeserializeObject<T>(jsonData);
    }
    else
    {
        throw new FileNotFoundException($"File not found: {filePath}");
    }
}

サンプルコード
var data = new DataModel
{
    Name = "Name1",
    Age = 30
};

var data2 = new DataModel
{
    Name = "Name2",
    Age = 10
};

List<DataModel> data_list = new List<DataModel>();
data_list.Add(data);
data_list.Add(data2);

string json = JsonConvert.SerializeObject(data_list, Formatting.Indented);
Console.WriteLine($"Serialized JSON: {json}");

// JSONデータをデシリアライズ(JSON → オブジェクト)
var deserializedData = JsonConvert.DeserializeObject<List<DataModel>>(json);
Console.WriteLine($"Deserialized Data - Name: {deserializedData[0].Name}, Age: {deserializedData[0].Age}");

// ファイルへ保存
SaveToJsonFile(data_list, "file.json");

// ファイルから読み出し
var loadedData = LoadFromJsonFile<List<DataModel>>("file.json");

参考ページ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?