當我將我的json錯誤響應從改造轉換爲對象時,我變空了。gson.fromJson正在返回null android的改造和gson
JSON字符串:
{"messageType":1,"hasErrors":true,"isSuccess":false,"message":"Invalid username or password"}
我創建的類:
public class ValidationContainer {
@SerializedName("messageType")
@Expose
private int MessageType;
@SerializedName("hasErrors")
@Expose
private Boolean HasErrors;
@SerializedName("isSuccess")
@Expose
private Boolean IsSuccess;
@SerializedName("message")
@Expose
private String Message;
public ValidationContainer() {
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
this.Message = message;
}
}
我的代碼:
public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
if (response.isSuccessful()) {
//TODO: Save response user properties to shared constants
Intent intent = new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
finish();
} else if (response.code() == 400) {
Gson gson = new GsonBuilder().create();
ValidationContainer container = new ValidationContainer();
try {
Log.e(Tag, response.errorBody().string());
container = gson.fromJson(response.errorBody().string(), ValidationContainer.class);
Log.e(Tag, container.getMessage());
} catch (IOException e) {
Log.e(Tag, e.getMessage());
}
}
}
當我登錄response.errorBody().string()
我得到如下:
在的build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.6.1'
我在做什麼錯?
嘗試UserDTO'改變''到後ValidationContainer'也試試。 –
@DheerubhaiBansal但我想轉換錯誤不是成功響應 –
請將您的庫版本更改爲'com.google.code.gson:gson:2.6.2' –