如何使用Java从给定的JSON对象中提取信息?
Got it, let's break down how to pull the details you need from that Jenkins FreeStyleBuild JSON using Java. I'll cover two widely used libraries—Jackson and Gson—plus a quick "no-POJO" approach for when you don't want to define classes upfront.
First, here's the JSON we're working with for reference:
{ "_class": "hudson.model.FreeStyleBuild", "actions": [ { "_class": "hudson.model.CauseAction", "causes": [ { "_class": "hudson.model.Cause$UserIdCause", "shortDescription": "Started by user SYSTEM", "userId": "SYSTEM", "userName": "SYSTEM" }, { "_class": "hudson.model.Cause$UserIdCause", "shortDescription": "Started by user SYSTEM", "userId": "SYSTEM", "userName": "SYSTEM" }, { "_class": "hudson.model.Cause$UserIdCause", "shortDescription": "Started by user SYS..." } ] } ] }
Option 1: Using Jackson (Object Mapper with POJOs)
Jackson is great for type-safe parsing by mapping JSON to Java objects.
Step 1: Add Jackson Dependency (Maven)
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- Use the latest stable version --> </dependency>
Step 2: Create POJO Classes
We'll define classes that mirror the JSON structure, using @JsonProperty to map underscore-prefixed fields:
import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class FreeStyleBuild { @JsonProperty("_class") private String className; private List<Action> actions; // Getters and setters (or use Lombok for brevity) public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<Action> getActions() { return actions; } public void setActions(List<Action> actions) { this.actions = actions; } } public class Action { @JsonProperty("_class") private String className; private List<Cause> causes; // Getters and setters public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<Cause> getCauses() { return causes; } public void setCauses(List<Cause> causes) { this.causes = causes; } } public class Cause { @JsonProperty("_class") private String className; private String shortDescription; private String userId; private String userName; // Getters and setters public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
Step 3: Parse and Extract Data
import com.fasterxml.jackson.databind.ObjectMapper; public class JsonParser { public static void main(String[] args) throws Exception { String jsonString = "{ /* Paste your full JSON here */ }"; ObjectMapper mapper = new ObjectMapper(); FreeStyleBuild build = mapper.readValue(jsonString, FreeStyleBuild.class); // Extract build class System.out.println("Build Class: " + build.getClassName()); // Extract all causes from the first CauseAction for (Action action : build.getActions()) { if ("hudson.model.CauseAction".equals(action.getClassName())) { for (Cause cause : action.getCauses()) { System.out.println("\nCause Description: " + cause.getShortDescription()); System.out.println("User ID: " + cause.getUserId()); System.out.println("User Name: " + cause.getUserName()); } } } } }
Option 2: Using Gson (Google's JSON Library)
Gson works similarly to Jackson but uses @SerializedName for field mapping.
Step 1: Add Gson Dependency (Maven)
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- Latest stable version --> </dependency>
Step 2: Create POJO Classes
import com.google.gson.annotations.SerializedName; import java.util.List; public class FreeStyleBuild { @SerializedName("_class") private String className; private List<Action> actions; // Getters and setters public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<Action> getActions() { return actions; } public void setActions(List<Action> actions) { this.actions = actions; } } // Action and Cause classes are identical to Jackson's version, just replace @JsonProperty with @SerializedName
Step 3: Parse and Extract Data
import com.google.gson.Gson; public class GsonParser { public static void main(String[] args) { String jsonString = "{ /* Paste your full JSON here */ }"; Gson gson = new Gson(); FreeStyleBuild build = gson.fromJson(jsonString, FreeStyleBuild.class); // Extract the same details as before System.out.println("Build Class: " + build.getClassName()); for (Action action : build.getActions()) { if ("hudson.model.CauseAction".equals(action.getClassName())) { for (Cause cause : action.getCauses()) { System.out.println("\nCause Description: " + cause.getShortDescription()); System.out.println("User ID: " + cause.getUserId()); System.out.println("User Name: " + cause.getUserName()); } } } } }
Option 3: No-POJO Approach (Jackson Tree Model)
If you don't want to create POJOs, you can use Jackson's tree model to navigate the JSON dynamically:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class TreeParser { public static void main(String[] args) throws Exception { String jsonString = "{ /* Paste your full JSON here */ }"; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(jsonString); // Get build class System.out.println("Build Class: " + root.get("_class").asText()); // Navigate to causes JsonNode actions = root.get("actions"); for (JsonNode action : actions) { if ("hudson.model.CauseAction".equals(action.get("_class").asText())) { JsonNode causes = action.get("causes"); for (JsonNode cause : causes) { System.out.println("\nCause Description: " + cause.get("shortDescription").asText()); // Handle optional fields (like userId might be missing in the third cause) if (cause.has("userId")) { System.out.println("User ID: " + cause.get("userId").asText()); } if (cause.has("userName")) { System.out.println("User Name: " + cause.get("userName").asText()); } } } } } }
This is handy for quick scripts or when the JSON structure might change occasionally.
All these approaches will let you pull out the build class, cause descriptions, user IDs, and usernames from your JSON. Let me know if you need help adapting any of this to your specific use case!
内容的提问来源于stack exchange,提问作者George Cimpoies

