我在Android中使用Retrofit以POST方式登录到带有API的服务器并回复它。当我插入服务器中已有的数据进行登录时,它将转到onResponse
,但是当我插入服务器中没有的数据时,将onFailure
但是在我的API中我处理的时候没有数据它会响应状态False
。这是转到onFailure
时的消息:
com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT但在第1行第56列为BEGIN_ARRAY $ .data
SignInService.java
public interface SignInService {
@FormUrlEncoded
@POST("api/signIn/")
Call<SignInRespone> signIn(@Field("email") String email,
@Field("password") String password);
}
SignInResponse.java
public class SignInRespone {
@SerializedName("success")
private boolean success;
@SerializedName("message")
private String message;
@SerializedName("data")
private Data data;
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data {
@SerializedName("id")
private int id;
@SerializedName("username")
private String username;
@SerializedName("email")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
SignInRequest.java
public class SignInRequest {
@SerializedName("email")
private String email;
@SerializedName("password")
private String password;
public SignInRequest(String email, String password) {
this.email = email;
this.password = password;
}
}
SignInActivity.java
public void signIn(){
signInService = ServiceGenerator.createService(SignInService.class);
Call<SignInRespone> call= signInService.signIn("jonh1@gmail.com","12345");
call.enqueue(new Callback<SignInRespone>() {
@Override
public void onResponse(Call<SignInRespone> call, Response<SignInRespone> response) {
Log.e(">>>>",response.body().getData().getEmail());
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
@Override
public void onFailure(Call<SignInRespone> call, Throwable t) {
Log.e(">>>>", t.toString());
}
});
}
答案 0 :(得分:0)
根据评论,当您完全登录成功时,服务器返回正确的对象,这就是为什么没有异常,但是当服务器上没有电子邮件时,它返回数据[]而不是数据对象,这就是为什么你会因为期待对象但服务器返回了一个数组。
解决方案: 返回数据:如果电子邮件不存在,则为null表单服务器