LoginSignup
0
1

C#におけるJsonDocument.Parse()の使い方

Posted at

JsonDocumentとは?

JsonDocumentは、.NETSystem.Text.Json名前空間に属するクラスです。JSONデータを読み取り、その内容にアクセスするための効率的な方法を提供します。このクラスは、JSONデータの読み込み、クエリ実行、データの抽出に使用されます。

JsonDocument.Parse()メソッドの基本

JsonDocument.Parse()は、文字列形式のJSONデータを解析し、JsonDocumentオブジェクトに変換するメソッドです。このメソッドを使用することで、JSONデータ内の個別の要素にアクセスしやすくなります。

使用方法

using System.Text.Json;

string jsonString = "{\"name\":\"John\", \"age\":30}";
JsonDocument doc = JsonDocument.Parse(jsonString);

上記の例では、JSON形式の文字列jsonStringJsonDocumentに解析しています。このdocオブジェクトを通じて、JSONデータの内容にアクセスできます。

要素へのアクセス

JsonElement root = doc.RootElement;
string name = root.GetProperty("name").GetString();
int age = root.GetProperty("age").GetInt32();

このコードでは、RootElementを使用してJSONのルート要素にアクセスし、GetPropertyメソッドで特定のプロパティを取得しています。

エラー処理

JSONデータの形式が不正な場合や、存在しないキーにアクセスしようとした場合、例外が発生する可能性があります。適切なエラー処理を行うことが重要です。

try
{
    JsonDocument doc = JsonDocument.Parse(jsonString);
    // その他の操作
}
catch (JsonException e)
{
    Console.WriteLine("JSONデータの解析中にエラーが発生しました。" + e.Message);
}
0
1
1

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