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

使用Retrofit 2.0获取Webservice请求结果及字段赋值问题

Troubleshooting Your Retrofit Response Issue

Hey there! Let’s work through this Retrofit problem together—it sounds like you’re struggling to pull the campo1 field from your webservice response, assign it to a variable, and print it. Chances are the issue ties into how you’re handling the asynchronous onResponse callback, or there’s a mismatch in your Model/ApiInterface setup. Let’s break this down across your three modules:

1. First, Validate Your Model Class

The most common culprit here is a mismatch between your JSON response fields and your Model class. Retrofit (with Gson) needs to map the JSON keys directly to your Model’s variables.

If your webservice returns JSON like this:

{
  "campo1": "your-desired-value",
  "otherField": "something-else"
}

Your Model should either:

  • Use the exact same variable name as the JSON key:
public class YourModel {
    private String campo1;
    // Add other fields as needed

    // Don't forget getter methods!
    public String getCampo1() {
        return campo1;
    }
}

OR use @SerializedName to map a different variable name to the JSON key:

import com.google.gson.annotations.SerializedName;

public class YourModel {
    @SerializedName("campo1")
    private String field1; // If you prefer this variable name

    public String getField1() {
        return field1;
    }
}

Pro tip: If you skip getters or misname fields, Retrofit won’t populate the values, leaving you with null.

2. Check Your ApiInterface Setup

Make sure your interface defines the correct HTTP method, endpoint, and returns a Call with your Model as the generic type (not ResponseBody or another incorrect type).

Example correct interface:

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    // Replace "your-endpoint" with your actual webservice path
    @GET("your-endpoint")
    Call<YourModel> fetchData();
}

Double-check that you’ve added the GsonConverterFactory when building Retrofit—without this, Retrofit can’t parse JSON into your Model:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://your-webservice-base-url.com/")
        .addConverterFactory(GsonConverterFactory.create()) // Critical!
        .build();

3. Fix the onResponse Callback & Asynchronous Timing

This is where most people get tripped up: Retrofit calls are asynchronous, meaning code outside the onResponse callback runs before the request finishes. If you try to access your variable outside onResponse, it’ll still be null.

Here’s the correct way to handle the response:

ApiInterface apiService = retrofit.create(ApiInterface.class);
Call<YourModel> call = apiService.fetchData();

// Use enqueue() for async execution (never use execute() on the main thread!)
call.enqueue(new Callback<YourModel>() {
    @Override
    public void onResponse(Call<YourModel> call, Response<YourModel> response) {
        // First, check if the request was successful (status code 2xx)
        if (response.isSuccessful()) {
            YourModel responseData = response.body();
            // Make sure responseData isn't null before accessing fields
            if (responseData != null) {
                // Assign campo1 to your variable HERE, inside onResponse
                String campo1Value = responseData.getCampo1();
                yourVariable = campo1Value;
                
                // Print it here too—this will work!
                System.out.println("campo1 value: " + campo1Value);
            } else {
                System.err.println("Response body is null");
            }
        } else {
            // Handle non-2xx status codes (e.g., 404, 500)
            System.err.println("Request failed with code: " + response.code());
        }
    }

    @Override
    public void onFailure(Call<YourModel> call, Throwable t) {
        // Handle network errors, timeouts, etc.
        System.err.println("Network error: " + t.getMessage());
    }
});

// ❌ DON'T do this—this code runs before onResponse finishes, so yourVariable is null
// System.out.println(yourVariable);

Common Pitfalls to Avoid

  • Forgetting getters: If your Model’s fields are private, you need getters to access them in onResponse.
  • Using execute() on the main thread: This will crash your app (Android) or block the thread—always use enqueue() for async calls.
  • BaseUrl mismatch: Ensure your baseUrl ends with a / and matches the start of your endpoint path.
  • Ignoring response.isSuccessful(): Even if the request goes through, a non-2xx status code means the response body won’t have your data.

Once you fix these areas, you should be able to successfully retrieve campo1, assign it to your variable, and print it out!

内容的提问来源于stack exchange,提问作者Emanuel Bessa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:57:20