JavaでJSONPathを用いたJSONデータの抽出と表示

JSONPathは、JSON構造内の特定フィールドをクエリするための強力な式言語です。Javaでは、com.jayway.jsonpathライブラリを活用することで、簡潔かつ柔軟にJSONデータを走査・抽出できます。以下に、実践的な手順と再設計されたコード例を示します。

基本的な実装フロー

以下の4ステップでJSONPathによる値抽出を実現します:

  • 依存関係の追加:MavenプロジェクトにJSONPathライブラリを導入
  • 入力JSONの準備:文字列またはファイルから有効なJSONを取得
  • パス式による評価$から始まるJSONPath式でノードを指定
  • 結果の整形出力:抽出値をコンソールや他の出力先へ送信

Maven依存設定

pom.xmlに次の記述を追加します(最新安定版を推奨):

<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <version>2.9.0</version>
</dependency>

サンプルJSONデータの定義

ネストされた構造を含む実用的な例として、ユーザー情報とその住所リストを表現します:

String payload = "{\n" +
  "  \"user\": {\n" +
  "    \"id\": 101,\n" +
  "    \"profile\": {\n" +
  "      \"fullName\": \"Yuki Tanaka\",\n" +
  "      \"email\": \"yuki@example.com\"\n" +
  "    },\n" +
  "    \"addresses\": [\n" +
  "      {\"type\": \"home\", \"zip\": \"100-0001\"},\n" +
  "      {\"type\": \"work\", \"zip\": \"150-0002\"}\n" +
  "    ]\n" +
  "  }\n" +
  "}";

JSONPathによる値の抽出処理

以下のように、DocumentContextを介して複数のパス式を一度に評価し、型安全に取得します:

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;

// JSON文字列をDocumentContextに変換(自動型推論対応)
DocumentContext context = JsonPath.parse(payload);

// 各フィールドを個別に抽出
int userId = context.read("$.user.id", Integer.class);
String userName = context.read("$.user.profile.fullName", String.class);
String primaryZip = context.read("$.user.addresses[0].zip", String.class);
List<String> allZips = context.read("$.user.addresses[*].zip", List.class);

結果の出力とフォーマット

抽出結果を一貫した形式で出力します:

System.out.printf("ID: %d%n", userId);
System.out.printf("氏名: %s%n", userName);
System.out.printf("自宅郵便番号: %s%n", primaryZip);
System.out.printf("全郵便番号: %s%n", String.join(", ", allZips));

実行結果例:

ID: 101
氏名: Yuki Tanaka
自宅郵便番号: 100-0001
全郵便番号: 100-0001, 150-0002

補足:エラー処理とオプション設定

存在しないパスに対する例外を抑制したい場合は、Option.SUPPRESS_EXCEPTIONSを有効化します:

Configuration config = Configuration.builder()
  .options(Option.SUPPRESS_EXCEPTIONS)
  .build();
DocumentContext safeContext = JsonPath.using(config).parse(payload);

タグ: jsonpath Java Maven jayway-jsonpath

5月16日 09:24 投稿