我正在使用Retrofit来从API检索数据。这是网址http://mindicador.cl/api,我需要检索名称为" uf"," dolar"," euro"和#34; utm",所有这四个人都在一个电话中。这是我基于json的Java类。
public class IEconomicoAPI {
private String version;
private String autor;
private String fecha;
@SerializedName(value = "uf", alternate = {"dolar", "euro", "utm"})
private IEconomicoObject uf;
/* All Getter and Setter methods */
}
这是我的调用方法,用于检索现在无效的数据。
void call() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MiIndicadorAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MiIndicadorAPI api = retrofit.create(MiIndicadorAPI.class);
final Call<IEconomicoAPI> iEconomicoAPICall = api.getAPI();
iEconomicoAPICall.enqueue(new Callback<IEconomicoAPI>() {
@Override
public void onResponse(Call<IEconomicoAPI> call, Response<IEconomicoAPI> response) {
String codigo = response.body().getUf().getCodigo();
if (codigo.equals("uf")) {
Log.e("info", "nombre: " + response.body().getUf().getNombre());
}
}
@Override
public void onFailure(Call<IEconomicoAPI> call, Throwable t) {
}
});
}
我正在考虑创建4个对象(一个用于uf,dolar,euro和utm)的解决方案,但我认为这是多余的,因为所有这些对象都具有相同的字段,更方便的方法应该只创建一个对象。无论如何,我希望你指导我如何解决这个问题。谢谢你的进步。
答案 0 :(得分:0)
您需要有4个不同的变量
private IEconomicoObject uf;
private IEconomicoObject dollar;
private IEconomicoObject euro;
private IEconomicoObject utm;
但理想情况下,我建议将API响应更改为类似
{
"version": "1.5.0",
"autor": "mindicador.cl",
"fecha": "2018-04-08T21:00:00.000Z",
"iEconomicoList": [
{
"codigo": "uf",
"nombre": "Unidad de fomento (UF)",
"unidad_medida": "Pesos",
"fecha": "2018-04-08T04:00:00.000Z",
"valor": 26966.89
},{
"codigo": "ivp",
"nombre": "Indice de valor promedio (IVP)",
"unidad_medida": "Pesos",
"fecha": "2018-04-08T04:00:00.000Z",
"valor": 28088.63
}
]
}
在这种情况下,模型可以是
public class IEconomicoAPI {
private String version;
private String autor;
private String fecha;
private List<IEconomicoObject> iEconomicoList;;
/* All Getter and Setter methods */
}