You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中反序列化JSON API响应并基于其调用另一API(集成Jenkins)

Hey there! Since you’re already comfortable with C#’s RestClient and Newtonsoft.Json for handling API deserialization and chained calls, let’s walk through how to replicate that exact workflow in Java—perfect for your Jenkins integration. Here’s a step-by-step breakdown tailored to your needs:

Java实现JSON API反序列化及链式API调用(对应C# RestClient/Newtonsoft.Json)

1. 准备依赖(Maven为例)

First up, we’ll use two mainstream Java libraries that mirror your C# toolset:

  • OkHttp: A lightweight HTTP client, just like RestSharp
  • Jackson: A robust JSON processing library, equivalent to Newtonsoft.Json

Add these dependencies to your pom.xml:

<dependencies>
    <!-- OkHttp HTTP客户端 -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.10.0</version>
    </dependency>
    <!-- Jackson JSON处理库 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

2. 定义匹配JSON结构的实体类

Just like you did in C#, create a Java class that maps directly to the JSON response from your first API. For example, if your first API returns this JSON:

{
  "buildId": 12345,
  "buildName": "Jenkins Nightly Build",
  "triggerApiUrl": "https://your-jenkins-instance/api/trigger-next"
}

Your corresponding Java class would look like this:

import com.fasterxml.jackson.annotation.JsonProperty;

public class FirstApiResponse {
    @JsonProperty("buildId")
    private int buildId;
    
    @JsonProperty("buildName")
    private String buildName;
    
    @JsonProperty("triggerApiUrl")
    private String triggerApiUrl;

    // Getters and Setters (Jackson needs these to access properties, just like C# properties)
    public int getBuildId() { return buildId; }
    public void setBuildId(int buildId) { this.buildId = buildId; }
    public String getBuildName() { return buildName; }
    public void setBuildName(String buildName) { this.buildName = buildName; }
    public String getTriggerApiUrl() { return triggerApiUrl; }
    public void setTriggerApiUrl(String triggerApiUrl) { this.triggerApiUrl = triggerApiUrl; }
}

注:@JsonProperty works exactly like C#’s [JsonProperty]—it maps JSON field names to your Java class properties if they don’t match exactly.

3. 反序列化第一个API的响应

Now let’s write code to call the first API and deserialize its response, mirroring your C# RestClient + Newtonsoft.Json logic:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class JenkinsApiClient {
    private final OkHttpClient httpClient = new OkHttpClient();
    private final ObjectMapper jsonMapper = new ObjectMapper();

    public FirstApiResponse fetchFirstApiData(String firstApiEndpoint) throws IOException {
        // Build the request (same as RestClient's Request object)
        Request request = new Request.Builder()
                .url(firstApiEndpoint)
                .get()
                .build();

        // Send the request and get the response (like RestClient.Execute)
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("First API request failed: " + response.code() + " " + response.message());
            }

            // Deserialize the response body to our entity class (equivalent to JsonConvert.DeserializeObject)
            assert response.body() != null;
            return jsonMapper.readValue(response.body().string(), FirstApiResponse.class);
        }
    }
}

4. 基于响应数据调用第二个API

Once we have the deserialized data from the first API, we can use it to trigger the second API call:

public void triggerSecondApi(FirstApiResponse firstResponse) throws IOException {
    // Extract the data we need from the first response (e.g., the trigger URL)
    String secondApiUrl = firstResponse.getTriggerApiUrl();
    // Alternatively, use buildId as a parameter: 
    // String secondApiUrl = "https://your-jenkins-instance/api/trigger?buildId=" + firstResponse.getBuildId();

    // Build the second API request (adjust method/body based on your actual API requirements)
    Request secondRequest = new Request.Builder()
            .url(secondApiUrl)
            .post(okhttp3.RequestBody.create("", okhttp3.MediaType.parse("application/json")))
            .build();

    try (Response secondResponse = httpClient.newCall(secondRequest).execute()) {
        if (!secondResponse.isSuccessful()) {
            throw new IOException("Second API request failed: " + secondResponse.code() + " " + secondResponse.message());
        }
        System.out.println("Second API called successfully! Response: " + secondResponse.body().string());
    }
}

5. 整合完整逻辑

Put it all together in a main method (or Jenkins-compatible entry point):

public static void main(String[] args) {
    JenkinsApiClient apiClient = new JenkinsApiClient();
    try {
        // Step 1: Call first API and deserialize response
        FirstApiResponse response = apiClient.fetchFirstApiData("https://your-api-endpoint/first-api");
        // Step 2: Use response data to call second API
        apiClient.triggerSecondApi(response);
    } catch (IOException e) {
        e.printStackTrace();
        // In Jenkins, you'd log this error and mark the build as failed here
    }
}

Jenkins Integration Tips

If you’re using this in Jenkins, here are two common approaches:

  • Jenkins Pipeline (Groovy): Groovy is fully compatible with Java syntax. You can add dependencies via @Grab and adapt the code directly in your Jenkinsfile:
    @Grab('com.squareup.okhttp3:okhttp:4.10.0')
    @Grab('com.fasterxml.jackson.core:jackson-databind:2.15.2')
    import okhttp3.OkHttpClient
    import okhttp3.Request
    import com.fasterxml.jackson.databind.ObjectMapper
    
    // Groovy simplifies getters/setters, so your entity class can be more concise
    class FirstApiResponse {
        int buildId
        String buildName
        String triggerApiUrl
    }
    
    // Rest of the logic mirrors the Java code above
    
  • Jenkins Plugin Development: If building a custom plugin, integrate the Java code directly into your plugin project, ensuring dependencies align with Jenkins’ plugin ecosystem rules.

内容的提问来源于stack exchange,提问作者LUCAS M SANTOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:02:05