【发布时间】:2016-08-23 10:45:35
【问题描述】:
我有 1 个请求,可以得到 2 个不同的响应:
登录名和密码正确时:
{
"token": "token..",
"expires": "2016-04-28T10:46:36+0000"
}
错误时:
{
"error": {
"id": "0123456789",
"code": 401,
"message": "invalid credentials"
}
}
虽然更正它解析成功,但是当我得到错误的响应(错误的登录名或密码)时,它返回 null(未解析)。
Error.java
public class Error {
@SerializedName("id")
@Expose
public String id;
@SerializedName("code")
@Expose
public int code;
@SerializedName("message")
@Expose
public String message;
public Error() {}
public Error(String id, int code, String message) {
this.id = id;
this.code = code;
this.message = message;
}
}
Auth.java
public class Auth {
@SerializedName("token")
@Expose
public String token;
@SerializedName("expires")
@Expose
public String expires;
@SerializedName("error")
@Expose
public Error error;
public Auth(String token, String expires, Error error) {
this.token = token;
this.expires = expires;
this.error = error;
}
public Auth() {
error = new Error();
}
}
ApiRequests.java
public interface ApiRequests {
@FormUrlEncoded
@POST("auth/token")
Call<Auth> auth(@Field("login") String login, @Field("password") String password);
}
Api.java
Gson gson = new GsonBuilder()
.setDateFormat(DATE_FORMAT)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_MAIN)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ApiRequests service = retrofit.create(ApiRequests.class);
Call<Auth> call = service.auth("login", "password");
call.enqueue(new Callback<Auth>() {
@Override
public void onResponse(Call<Auth> call, Response<Auth> response) {
Auth responseBody = response.body(); // null when login/password are wrong
}
@Override
public void onFailure(Call<Auth> call, Throwable t) {
}
});
build.gradle
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.google.code.gson:gson:2.6.2'
}
【问题讨论】:
标签: android json gson retrofit retrofit2