如何用Java+Selenium提取JSON中Service1的data节点数据?
Got it, let's tackle this problem step by step. I assume you've already captured the full JSON string through your Selenium script (maybe from page source, an API response, or a hidden DOM element). The goal is to extract only the data nodes under the Service1 array, ignoring the test nodes entirely.
Below are two reliable implementations using the most common JSON processing libraries in Java—Jackson and Gson. Pick whichever fits your project's existing dependencies.
使用Jackson库实现
First, add the Jackson Databind dependency to your project (if you don't have it already):
Maven Dependency
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- Use the latest stable version --> </dependency>
Java Code Example
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class JsonExtractor { public static void main(String[] args) { // Replace this with your actual JSON string captured via Selenium String fullJson = "{ \"Service1\": [ { \"data\": { \"id\": 1, \"name\": \"Sample Data 1\" }, \"test\": { \"status\": \"pass\" } }, { \"data\": { \"id\": 2, \"name\": \"Sample Data 2\" }, \"test\": { \"status\": \"fail\" } } ] }"; ObjectMapper objectMapper = new ObjectMapper(); List<JsonNode> service1DataList = new ArrayList<>(); try { // Parse the full JSON into a JsonNode JsonNode rootNode = objectMapper.readTree(fullJson); // Get the Service1 array node JsonNode service1Array = rootNode.get("Service1"); if (service1Array != null && service1Array.isArray()) { // Iterate through each element in the Service1 array for (JsonNode serviceItem : service1Array) { // Extract the "data" node (ignore "test" node) JsonNode dataNode = serviceItem.get("data"); if (dataNode != null) { service1DataList.add(dataNode); // Optional: Convert dataNode to a custom POJO if needed // DataPojo data = objectMapper.treeToValue(dataNode, DataPojo.class); } } } // Print or use the extracted data nodes for (JsonNode data : service1DataList) { System.out.println("Extracted Data: " + data.toPrettyString()); } } catch (IOException e) { e.printStackTrace(); // Handle JSON parsing errors in your automation script (e.g., log to test report) } } // Optional: Define a POJO to map the data node (if you need strongly typed objects) static class DataPojo { private int id; private String name; // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
使用Gson库实现
If you prefer using Gson instead, add this dependency first:
Maven Dependency
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- Use the latest stable version --> </dependency>
Java Code Example
import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.List; public class GsonJsonExtractor { public static void main(String[] args) { // Replace with your captured JSON string from Selenium String fullJson = "{ \"Service1\": [ { \"data\": { \"id\": 1, \"name\": \"Sample Data 1\" }, \"test\": { \"status\": \"pass\" } }, { \"data\": { \"id\": 2, \"name\": \"Sample Data 2\" }, \"test\": { \"status\": \"fail\" } } ] }"; JsonElement jsonElement = JsonParser.parseString(fullJson); JsonObject rootObject = jsonElement.getAsJsonObject(); List<JsonObject> service1DataList = new ArrayList<>(); // Get the Service1 array if (rootObject.has("Service1")) { JsonArray service1Array = rootObject.getAsJsonArray("Service1"); // Iterate through each item in the array for (JsonElement element : service1Array) { JsonObject serviceItem = element.getAsJsonObject(); // Extract the "data" object if (serviceItem.has("data")) { JsonObject dataObject = serviceItem.getAsJsonObject("data"); service1DataList.add(dataObject); // Optional: Convert to custom POJO // DataPojo data = new Gson().fromJson(dataObject, DataPojo.class); } } } // Output the extracted data for (JsonObject data : service1DataList) { System.out.println("Extracted Data: " + data.toString()); } } // Optional: Same POJO as before for mapping static class DataPojo { private int id; private String name; // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
Quick Notes
- Replace the
fullJsonstring with the actual JSON you capture via Selenium (e.g., if pulling from a hidden element, usedriver.findElement(By.id("json-container")).getText();). - If you need to work with strongly typed objects instead of generic JSON nodes, uncomment the POJO conversion lines and adjust the
DataPojoclass to match your realdatastructure. - Make sure to handle exceptions properly in your automation script (e.g., log errors to your test reporting tool instead of just printing stack traces).
内容的提问来源于stack exchange,提问作者akhouri
相关产品推荐
相关产品推荐

