嗨,我是Android的新用戶,因此如果有任何愚蠢的代碼,請耐心等待。Retrofit 2.0響應失敗,如果使用Realm對象封裝,則返回null for throwback
所以我在這種情況下登錄一個簡單的API,這是在我的代碼的用戶對象:
public class User extends RealmObject {
@SerializedName("id")
private String ID;
@SerializedName("username")
private String username;
@SerializedName("token_type")
private String tokenType;
@SerializedName("token")
private String token;
//Setter and Getter goes here
}
登錄API接口:
public interface LoginAPI {
@POST("api/v1/login")
Call<User> login(@Body JsonObject user);
}
這是實施請求我的登錄API:
//OnClickListener
View.OnClickListener loginButtonClicked = new View.OnClickListener() {
public void onClick(View v) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", emailEditText.getText().toString());
jsonObject.addProperty("password", passwordEditText.getText().toString());
Retrofit loginRequest = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI loginAPI = loginRequest.create(LoginAPI.class);
Call<User> call = loginAPI.login(jsonObject);
call.enqueue(LoginFragment.this);
}
};
//API Callback
@Override
public void onResponse(Response<User> response, Retrofit retrofit) {
User user = response.body();
Realm realm = Realm.getInstance(getContext());
realm.beginTransaction();
realm.copyToRealmOrUpdate(user);
realm.commitTransaction();
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(getActivity(), "Failed " + t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
問題是它總是調用onFailure回調函數並返回對於Throwable t值,爲NULL。
我的代碼是工作時,我的用戶對象不是擴展RealmObject,但這意味着我必須創建2對象Retrofit和領域。
有沒有什麼辦法可以讓我使用1個對象來進行Retrofit和Realm實現,或者我的代碼中是否有任何錯誤或遺漏? 非常感謝。
是的我嘗試了像你提到的GSON初始化,但它忽略了我的用戶對象上的'@ SerializedName'。有什麼方法可以讓GSON運行'@ SerializedName'?真的謝謝 – KidouKid