fdg g fdg g - 9 months ago 36
Android Question

How to fix Expected BEGIN_OBJECT in Android

I want send some data to server, but I am getting an error message in AndroidMonitor as below

failed
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $


Here is my code:

Retrofit Interface :

@POST("user")
Call<ServerResponse> operation(@Body ServerRequest request);


Here is the method that includes the call to the endpoint via retrofit

private void registerProcess(String name, String email, String password, final View view) {

Gson gson = new GsonBuilder()
.setLenient()
.create();

OkHttpClient client = new OkHttpClient();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

Retrofit_ApiInterface requestInterface = retrofit.create(Retrofit_ApiInterface.class);

User user = new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);

ServerRequest request = new ServerRequest();
request.setOperation(Constants.REGISTER_OPERATION);
request.setUser(user);

Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(view, resp.getMessage(), Snackbar.LENGTH_LONG).show();
registerLoad.setVisibility(View.INVISIBLE);
Log.e(Constants.TAG, resp.getMessage());
registerSend.setVisibility(View.GONE);
}

@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
registerLoad.setVisibility(View.INVISIBLE);
registerSend.setVisibility(View.VISIBLE);
Log.d(Constants.TAG, "failed" + "\n" + t.getLocalizedMessage() + "");
Snackbar.make(view, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});


ServerRequest :

public class ServerRequest {

private String operation;
private User user;

public void setOperation(String operation) {
this.operation = operation;
}

public void setUser(User user) {
this.user = user;
}
}


Server Response :

public class ServerResponse {

private String result;
private String message;
private User user;

public String getResult() {
return result;
}

public String getMessage() {
return message;
}

public User getUser() {
return user;
}
}


How can I fix it?

Answer Source

Your problem is very simple.
You should add "/" into your POST method interface.
Such as this :

@POST("user/")
Call<ServerResponse> operation(@Body ServerRequest request);

Try this.