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

329行目: 329行目:
           await StaticJsonFileWriter.WriteJsonFileAsync(writeFilePath, person);
           await StaticJsonFileWriter.WriteJsonFileAsync(writeFilePath, person);
       }
       }
    }
}
</syntaxhighlight>
<br><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 JsonReader
{
    public async Task ReadJsonFileAsync(string filePath)
    {
      try
      {
          using (var fileStream = File.OpenRead(filePath))
          using (var streamReader = new StreamReader(fileStream))
          using (var jsonReader = new JsonTextReader(streamReader))
          {
            var jsonObject = await JObject.LoadAsync(jsonReader);
            // JSONデータの処理
            Console.WriteLine("アプリの説明: " + jsonObject["appDesc"]["description"]);
            Console.WriteLine("アプリの名前: " + jsonObject["appName"]["message"]);
            // 配列の処理
            var impArray = jsonObject["appName"]["imp"].ToObject<string[]>();
            Console.WriteLine("重要な特徴:");
            foreach (var item in impArray)
            {
                Console.WriteLine("- " + item);
            }
          }
      }
      catch (FileNotFoundException)
      {
          Console.WriteLine("エラー: 指定されたJSONファイルが存在しない");
      }
      catch (JsonException ex)
      {
          Console.WriteLine($"エラー: JSONの解析中にエラーが発生: {ex.Message}");
      }
      catch (Exception ex)
      {
          Console.WriteLine($"予期せぬエラーが発生: {ex.Message}");
      }
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="c#">
class Program
{
    static async Task Main(string[] args)
    {
      // JSONファイルの読み込み
      var reader = new JsonReader();
      await reader.ReadJsonFileAsync("input.json");
     }
     }
  }
  }