「C Sharpの基礎 - JSON」の版間の差分

ナビゲーションに移動 検索に移動
608行目: 608行目:
   
   
       await writer.WriteJsonFileAsync("sample.json", jsonObject);
       await writer.WriteJsonFileAsync("sample.json", jsonObject);
    }
}
</syntaxhighlight>
<br>
==== LINQ to JSON : JSONファイルの変更 ====
以下の例では、下記に示すJSONファイルの"appName"オブジェクトの"imp"配列の値を["hoge", "piyo"]に変更している。<br>
<br>
* 変更前のJSONファイル
<syntaxhighlight lang="json">
{
    "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
    },
    "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
    }
}
</syntaxhighlight>
<br>
# JsonModifierクラスのインスタンスを生成する。
# JSONファイルを読み込み、JObject.Parseメソッドを使用してJSONオブジェクトに変換する。
# JSONオブジェクトから、jsonObject["appName"]["imp"] = new JArray("hoge", "piyo");を使用して、"appName"オブジェクトの"imp"配列の値を["hoge", "piyo"]に変更する。
# 変更したJSONオブジェクトを新しいファイルに書き込む。
<br>
<syntaxhighlight lang="c#">
using System;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class JsonModifier
{
    public async Task ModifyAndWriteJsonFileAsync(string inputFilePath, string outputFilePath)
    {
      try
      {
          // JSONファイルを読み込む
          string jsonContent = await File.ReadAllTextAsync(inputFilePath);
          JObject jsonObject = JObject.Parse(jsonContent);
          // appName.impの値を変更
          jsonObject["appName"]["imp"] = new JArray("hoge", "piyo");
          // 変更したJSONを新しいファイルに書き込む
          await WriteJsonFileAsync(outputFilePath, jsonObject);
      }
      catch (FileNotFoundException ex)
      {
          Console.WriteLine($"エラー: 入力ファイルが存在しない: {ex.Message}");
      }
      catch (JsonException ex)
      {
          Console.WriteLine($"エラー: JSONの解析中にエラーが発生: {ex.Message}");
      }
      catch (Exception ex)
      {
          Console.WriteLine($"予期せぬエラーが発生: {ex.Message}");
      }
    }
    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)
    {
      string inputFilePath  = "sample.json";
      string outputFilePath = "newsample.json";
      var jsonModifier = new JsonModifier();
      await jsonModifier.ModifyAndWriteJsonFileAsync(inputFilePath, outputFilePath);
     }
     }
  }
  }

案内メニュー