【问题标题】:Retrofit 2: response returns null when response code is 200改造 2:响应代码为 200 时,响应返回 null
【发布时间】:2017-06-28 08:25:24
【问题描述】:

我正在尝试使用 Retrofit 2 做一个简单的 Web 服务。 网址为:https://www.metaweather.com/api/location/1100661/2017/6/26/

列出天气= response.body();

当我尝试从响应中获取数据时,它为空。即使响应码是 200。

我使用http://www.jsonschema2pojo.org/ 制作了各种版本的 Weather 类。结果是一样的。下面列出了一些类。有人能告诉我我的代码有什么问题吗?谢谢

主活动:

public class MainActivity extends AppCompatActivity {

private static final String API_BASE_URL = "https://www.metaweather.com/";

@BindView(R.id.tv_weather)
TextView mWeatherTv;

@BindView(R.id.bn_weather)
AppCompatButton mWeatherBn;

@BindView(R.id.tv_details)
TextView mDetailsTv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ButterKnife.bind(this);

}

public void fetchData(View view) {
    Toast.makeText(getApplicationContext(), "fetch data", Toast.LENGTH_SHORT).show();

    try {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiClient client = retrofit.create(ApiClient.class);
        Call<List<Weather>> call = client.getWeatherData();

        call.enqueue(new Callback<List<Weather>>() {
            @Override
            public void onResponse(Call<List<Weather>> call, Response<List<Weather>> response) {
                Log.v("testing", "Response is " + response.raw().toString());
                if (!response.isSuccessful()){
                    return;
                }

                List<Weather> weather= response.body();

                String details = "";
                Log.v("testing", weather.toString());

                if (weather != null && weather.size()>0){
                    for (int i = 0; i < weather.size(); i++){
                        String name = weather.get(i).getWeatherStateAbbr();

                        details += "\n\nweather: " + name;
                    }
                    mDetailsTv.setText(details);
                    Log.v("testing", "weather is " + details);
                }
            }

            @Override
            public void onFailure(Call<List<Weather >> call, Throwable t) {
                Log.v("testing", "Failed " + String.valueOf(t));

            }
        });
    } catch (Exception e){
        Log.e("exception", String.valueOf(e));
    }
}

}

ApiClient:

import java.util.List;

import me.anky.brisbaneweather.Weather;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiClient {

    // https://www.metaweather.com/api/location/1100661/2017/6/26/
    @GET("api/location/1100661/2017/6/26/")
    Call<List<Weather>> getWeatherData();
}

天气

public class Weather {
    private long id;
    private String weatherStateName;
    private String weatherStateAbbr;
    private String windDirectionCompass;
    private String created;
    private String applicableDate;
    private double minTemp;
    private double maxTemp;
    private double theTemp;
    private double windSpeed;
    private double windDirection;
    private double airPressure;
    private long humidity;
    private Object visibility;
    private long predictability;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getWeatherStateName() {
        return weatherStateName;
    }

    public void setWeatherStateName(String weatherStateName) {
        this.weatherStateName = weatherStateName;
    }

    public String getWeatherStateAbbr() {
        return weatherStateAbbr;
    }

    public void setWeatherStateAbbr(String weatherStateAbbr) {
        this.weatherStateAbbr = weatherStateAbbr;
    }

    public String getWindDirectionCompass() {
        return windDirectionCompass;
    }

    public void setWindDirectionCompass(String windDirectionCompass) {
        this.windDirectionCompass = windDirectionCompass;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public String getApplicableDate() {
        return applicableDate;
    }

    public void setApplicableDate(String applicableDate) {
        this.applicableDate = applicableDate;
    }

    public double getMinTemp() {
        return minTemp;
    }

    public void setMinTemp(double minTemp) {
        this.minTemp = minTemp;
    }

    public double getMaxTemp() {
        return maxTemp;
    }

    public void setMaxTemp(double maxTemp) {
        this.maxTemp = maxTemp;
    }

    public double getTheTemp() {
        return theTemp;
    }

    public void setTheTemp(double theTemp) {
        this.theTemp = theTemp;
    }

    public double getWindSpeed() {
        return windSpeed;
    }

    public void setWindSpeed(double windSpeed) {
        this.windSpeed = windSpeed;
    }

    public double getWindDirection() {
        return windDirection;
    }

    public void setWindDirection(double windDirection) {
        this.windDirection = windDirection;
    }

    public double getAirPressure() {
        return airPressure;
    }

    public void setAirPressure(double airPressure) {
        this.airPressure = airPressure;
    }

    public long getHumidity() {
        return humidity;
    }

    public void setHumidity(long humidity) {
        this.humidity = humidity;
    }

    public Object getVisibility() {
        return visibility;
    }

    public void setVisibility(Object visibility) {
        this.visibility = visibility;
    }

    public long getPredictability() {
        return predictability;
    }

    public void setPredictability(long predictability) {
        this.predictability = predictability;
    }
}

我的一些依赖项如下:

compile 'com.squareup.okhttp3:okhttp:3.6.0'
testCompile 'junit:junit:4.12'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.jakewharton:butterknife:8.6.0'

【问题讨论】:

  • 你懂java吗?这是正常的List.ToString() 结果 - 看起来应该
  • 我其实并不知道。我把它放在日志中的原因是我得到了空响应。我想看看列表是什么。

标签: android retrofit


【解决方案1】:

您使用了GsonConverterFactory,但没有以正确的方式实现。这是链接:Consuming APIs with Retrofit

提示:带有GsonConverterFactory 的改造构建器只接受带有 Gson @annotation 的 POJO 类。将您的 Weather 类更改为 WeatherPojo 类,如下所示:

    public class WeatherPojo {
    @SerializedName("id")
    @Expose
    public long id;

    @SerializedName("weatherStateName")
    @Expose
    public String weatherStateName;

    @SerializedName("weatherStateAbbr")
    @Expose
    public String weatherStateAbbr;

    @SerializedName("windDirectionCompass")
    @Expose
    public String windDirectionCompass;

    @SerializedName("created")
    @Expose
    public String created;

    @SerializedName("applicableDate")
    @Expose
    public String applicableDate;

    @SerializedName("minTemp")
    @Expose
    public double minTemp;

    @SerializedName("maxTemp")
    @Expose
    public double maxTemp;

    @SerializedName("theTemp")
    @Expose
    public double theTemp;

    @SerializedName("windSpeed")
    @Expose
    public double windSpeed;

    @SerializedName("windDirection")
    @Expose
    public double windDirection;

    @SerializedName("airPressure")
    @Expose
    public double airPressure;

    @SerializedName("humidity")
    @Expose
    public long humidity;

    @SerializedName("visibility")
    @Expose
    public Object visibility;

    @SerializedName("predictability")
    @Expose
    public long predictability;
}

这调用 POJO(Plane old java object)。您可以将此类用作模型或创建新类并将 POJO 转换为您的 ModelObject。

因为这个原因,我使用公共字段而不是 getter 和 setter。 Public field vs getter and setter

【讨论】:

  • 感谢您的回答以及关于 getter 和 setter 的额外说明。很遗憾,我检查了 Retrofit 上的许多其他链接,但没有检查 CodePath 上的链接。谢谢。
【解决方案2】:

在 Weather.class 中生成 toString 方法。应该是这样的:

@Override
public String toString() {
   return "Weather{" +
        "id='" + id + '\'' +
        ", weatherStateName =" + weatherStateName +
        ", FIELD_NAME =" + FIELD +
        '}';
   }

【讨论】:

  • @AnkyAn 尝试让 Weather 类实现 Serializable
  • 谢谢@lzya Pitersky。我尝试过这个。它没有用。我以前见过这个 toString() ,但没有看到任何关于它的功能的解释。它有什么作用?
猜你喜欢
  • 2021-05-04
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多