溫馨提示×

jsonpath java 怎么解決匹配問題

小樊
112
2024-11-27 03:14:38
欄目: 編程語言

在Java中,您可以使用com.jayway.jsonpath庫來處理JSON數據。要解決匹配問題,您需要使用正確的JSON路徑表達式。以下是一些常見的JSON路徑表達式示例:

  1. $.store.book[*].author:選擇store對象中的所有book數組元素的作者。
  2. $.store.book[?(@.price < 10)]:選擇store對象中的所有價格小于10的book元素。
  3. $..author:選擇所有對象中的作者。

要在Java中使用這些表達式,請按照以下步驟操作:

  1. 首先,將com.jayway.jsonpath庫添加到項目的依賴項中。如果您使用Maven,可以在pom.xml文件中添加以下依賴項:
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>
  1. 然后,使用以下代碼示例處理JSON數據:
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

import java.io.IOException;
import java.util.Map;

public class JsonPathExample {
    public static void main(String[] args) throws IOException {
        String json = "{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"price\":8.95}]}}";

        DocumentContext documentContext = JsonPath.parse(json);

        // 示例1: 獲取所有作者
        String authors = documentContext.read("$.store.book[*].author");
        System.out.println("Authors: " + authors);

        // 示例2: 獲取價格小于10的書籍作者
        String authorsWithLowPrice = documentContext.read("$.store.book[?(@.price < 10)]");
        System.out.println("Authors with low price: " + authorsWithLowPrice);

        // 示例3: 獲取所有作者(遞歸)
        String allAuthors = documentContext.read("$..author");
        System.out.println("All authors: " + allAuthors);
    }
}

這個示例將解析給定的JSON字符串,并使用不同的JSON路徑表達式提取作者信息。請根據您的需求調整這些表達式以解決匹配問題。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女