1
I am trying to consume data from an API using retrofit, but whenever I try to connect it returns this error. I’m using a class that is an Array of these objects (Sisalfacatalog) and throwing the return inside it, but it doesn’t work. Follow the code:
The interface of the service:
public interface SisalfaService {
public static final String BASE_URL = "https://app.sisalfa.dcx.ufpb.br/v1/api/";
@GET("contexts")
Call<SisalfaCatalog> listPalavras();
}
The class with the Object Array:
public class SisalfaCatalog {
public ArrayList<Palavra> palavras;
}
Content of the API:
[
{
"id": 1,
"name": "Sala",
"image": "https://app.sisalfa.dcx.ufpb.br/v1/static/images/dababcd96ab5f7854f820ff926c9acaa.jpg",
"sound": "",
"video": "",
"createdAt": "2018-06-22T19:31:18.745Z",
"updatedAt": "2018-06-22T19:31:18.745Z",
"user": {
"id": 1,
"username": "neto",
"email": "[email protected]",
"firstName": "José",
"lastName": "Antonio da Silva Neto",
"photo": null
}
},
And the main with the service call:
retrofit = new Retrofit.Builder()
.baseUrl(SisalfaService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
SisalfaService service = retrofit.create(SisalfaService.class);
Call<SisalfaCatalog> call = service.listPalavras();
call.enqueue(new Callback<SisalfaCatalog>() {
@Override
public void onResponse(Call<SisalfaCatalog> call, Response<SisalfaCatalog> response) {
if(!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Errr, a conexão não deu certo", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bem, deu certo aparentemente", Toast.LENGTH_LONG).show();
SisalfaCatalog catalog = response.body();
for(Palavra p : catalog.palavras) {
Log.i("Nome: ", p.getName());
Log.i("Id: ", ""+p.getId());
Log.i("Url: ", p.getImage());
}
}
}
@Override
public void onFailure(Call<SisalfaCatalog> call, Throwable t) {
Toast.makeText(MainActivity.this, "Errr, não deu certo. "+t.getMessage(), Toast.LENGTH_LONG).show();
Log.i("Erro: ", t.getMessage());
}
});
The coming JSON begins with
[
, so it’s an array. The code expected it to be an object. Inside the array is an object (starting with{
), I believe he expected it to be this object. When it is array you have to treat as array and when it is object treat as object. I don’t know the API you’re using but I’d give you more details.– Piovezan
as I do to treat as array? in the interface I place an Array inside the call?
– Ana Paula Lima
Like I said, I don’t know the API you’re using.
– Piovezan
All right. I made this modification on the interface and it worked.
– Ana Paula Lima
Nice work. The reverse is also possible, bring only one object in JSON, but apparently what you wanted was Arraylist.
– Piovezan