改造 returns 空数据

Retrofit returns null data

我有问题 - 我不知道为什么 body returns null 这里是我的模型。

package com.example.currencyapp.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

public class Rates implements Serializable {

    @SerializedName("CAD")
    @Expose
    private String cad;

    public Rates(String cad) {
        this.cad = cad;
        
    }

    public Rates() {
    }

    public String getCad() {
        return cad;
    }

   
}

这是我的 json

    {
        "rates": {
            "CAD": 1.5399,
           }
    }

这是我的服务

    import com.example.currencyapp.model.Rates;
    
    import retrofit2.Call;
    import retrofit2.http.GET;
    import retrofit2.http.Query;
    
    public interface GetCurrencyDataService {
        @GET("/latest")
        Call<Rates> getCurrencyData();
    } 

和我的改造实例

    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    public class RetrofitInstance {
        private static Retrofit retrofit;
        private static final String BASE_URL = "https://api.exchangeratesapi.io";
    
        public static Retrofit getRetrofitInstance() {
            if (retrofit == null) {
                retrofit = new retrofit2.Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

JSON 您呈现的对象期望您的模型是:

public class CadObject implements Serializable {
    @SerializedName("rates")
    @Expose
    private Rates rates;

    ...

    class Rates implements Serializable {

        @SerializedName("CAD")
        @Expose
        private String cad;

        ...
    }
}

原因是您有一个 JSON 对象,其中包含一个 JSON 对象,该对象包含一个字符串值。

如果您希望当前模型正常工作JSON对象结构应该如下所示:

{
    "CAD": 1.5399
}