Error with retrofit

Asked

Viewed 216 times

1

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

public interface RestApi {

@GET("/posts")
Call<Model[]> getWheatherReport();

}

public class Mainactivity extends Appcompatactivity {

String url = "http://jsonplaceholder.typicode.com/posts";
TextView txt_city, txt_status, txt_humidity, txt_pressure;

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

    txt_city = (TextView) findViewById(R.id.txt_city);
    txt_status = (TextView) findViewById(R.id.txt_status);
    txt_humidity = (TextView) findViewById(R.id.txt_humidity);
    txt_pressure = (TextView) findViewById(R.id.txt_press);


    getReport();
}

void getReport() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RestApi service = retrofit.create(RestApi.class);

    Call<Model[]> call = service.getWheatherReport();

    call.enqueue(new Callback<Model[]>() {
        @Override
        public void onResponse(Response<Model[]> response, Retrofit retrofit) {
            Log.v("CONSOLES", "--> "+response.body());
            try {

                Integer userId = response.body()[0].getUserId();

                Integer id = response.body()[0].getId();

                String title = response.body()[0].getTitle().toString();

                String body = response.body()[0].getBody().toString();

                txt_city.setText("city  :  " + userId);
                txt_status.setText("status  :  " + id);
                txt_humidity.setText("humidity  : " + title);
                txt_pressure.setText("pressure  :  " + body);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(Throwable t) {
            Log.v("CONSOLES-ERRO", "--> "+t.toString());
        }
    });
}

}

I have tried several tutorials and continues the error.

1 answer

-1


Fala Roberto,

Your problem is in Model, to get it in array mode, you are doing wrong in Retrofit:

Would have to be:

Callback<List<Model>>

in place of:

Callback<Model[]>

Hugs.

  • Leonardo speaks.

  • Have you also changed where you have Call<Model[]>?? Post your Model file so I can take a look, you can edit your post. Hugs.

  • 1

    Leonardo, already solved. The error was in /posts/posts/ in the url.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.