2
У меня есть 1 запрос и может есть 2 разных ответов:Как разобрать JSON с модифицированной и gson асинхронно
Когда Логин и пароль правильны:
{
"token": "token..",
"expires": "2016-04-28T10:46:36+0000"
}
когда неправильно:
{
"error": {
"id": "",
"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'
}
добавлено «реализует Serializable», в «onResponse()» метод «response.body() = null». "response.code() = 401", почему не 200? Я проверил его на «www.hurl.it» и сервер, возвращающий JSON, и код 401 –
Проверьте свой API, но это означает, что аутентификация не удалась – yozzy