📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

458行目: 458行目:
  </syntaxhighlight>
  </syntaxhighlight>
<br>
<br>
以下の例では、上記のクラスを使用してJSONファイルを読み込んでいる。<br>
  <syntaxhighlight lang="c#">
  <syntaxhighlight lang="c#">
  class Program
  class Program
466行目: 467行目:
       var reader = new JsonReader();
       var reader = new JsonReader();
       await reader.ReadJsonFileAsync("sample.json");
       await reader.ReadJsonFileAsync("sample.json");
    }
}
</syntaxhighlight>
<br>
==== LINQ to JSON : JSONファイルの書き込み ====
以下の例では、LINQ to JSON、非同期処理、ストリーミング処理を使用して、JSONファイルの書き込んでいる。<br>
<br>
FileStreamクラスを使用してストリーミング処理することにより、大きなJSONファイルを扱う場合にもメモリ効率が向上している。<br>
<br>
* 書き込むJSONファイル
<syntaxhighlight lang="json">
{
    "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
    },
    "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="c#">
using System;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class JsonWriter
{
    public async Task WriteJsonFileAsync(string filePath, JObject jsonObject)
    {
      try
      {
          using (var fileStream = File.Create(filePath))
          using (var streamWriter = new StreamWriter(fileStream))
          using (var jsonWriter = new JsonTextWriter(streamWriter))
          {
            jsonWriter.Formatting = Formatting.Indented;
            await jsonObject.WriteToAsync(jsonWriter);
          }
          Console.WriteLine("JSONファイルの書き込みが完了");
      }
      catch (IOException ex)
      {
          Console.WriteLine($"エラー: ファイルの書き込み中にエラーが発生: {ex.Message}");
      }
      catch (JsonException ex)
      {
          Console.WriteLine($"エラー: JSONの生成中にエラーが発生: {ex.Message}");
      }
      catch (Exception ex)
      {
          Console.WriteLine($"予期せぬエラーが発生: {ex.Message}");
      }
    }
}
</syntaxhighlight>
<br>
以下の例では、上記のクラスを使用してJSONファイルを書き込んでいる。<br>
<syntaxhighlight lang="c#">
class Program
{
    static async Task Main(string[] args)
    {
      // JSONファイルの書き込み
      var writer = new JsonWriter();
      var jsonObject = new JObject
      {
          ["appDesc"] = new JObject
          {
            ["description"] = "SomeDescription",
            ["message"] = "SomeMessage"
          },
          ["appName"] = new JObject
          {
            ["description"] = "Home",
            ["message"] = "welcome",
            ["imp"] = new JArray { "awesome", "best", "good" }
          }
      };
      await writer.WriteJsonFileAsync("sample.json", jsonObject);
     }
     }
  }
  }