retrofitにおけるerrorbodyの読み取り
2256 ワード
retrofit 2.0では、成功を返すデータの取得には通常successとerrorの2種類があります.最初のsuccessの場合は議論しませんが、errorbodyのjsonフィールドを取得する方法を見てみましょう.
例:
Errorbodyのjson:
{「timestamp」:1524013180129、「error」:「Precondition Failed」、「exception」:「com.exception.Http 412 Exception」、「message」:「口座が存在しないか、口座情報がまだ完備していない」、「path」:「/v 1/accounts/」、「code」:412}
各フィールドを取得するとします.次に、クラスのjavabeanを設定します.
処理時:
例:
Errorbodyのjson:
{「timestamp」:1524013180129、「error」:「Precondition Failed」、「exception」:「com.exception.Http 412 Exception」、「message」:「口座が存在しないか、口座情報がまだ完備していない」、「path」:「/v 1/accounts/」、「code」:412}
各フィールドを取得するとします.次に、クラスのjavabeanを設定します.
public class AccidErrorDataBase {
@SerializedName("timestamp")
private String timestamp;
@SerializedName("error")
private String error;
@SerializedName("exception")
private String exception;
@SerializedName("message")
private String message;
@SerializedName("path")
private String path;
@SerializedName("code")
private String code;
public String getTimestamp() {
return timestamp;
}
public String getError() {
return error;
}
public String getException() {
return exception;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public String getPath() {
return path;
}
public String getCode() {
return code;
}
}
処理時:
try {
//Toast.makeText(MainActivity.this,response.errorBody().string(),Toast.LENGTH_SHORT).show();
//Log.i(" ",response.errorBody().string());
Gson gson = new Gson(); // errorBody().string() ,
AccidErrorDataBase errorResponse = gson.fromJson(
response.errorBody().string(),
AccidErrorDataBase.class);
Log.i("code",errorResponse.getCode());
if ("412".equals(errorResponse.getCode())){
Intent intentmain=new Intent(MainActivity.this,SetmailActivity.class);
intentmain.putExtra("jwt",JWT);
intentmain.putExtra("vid",VID);
startActivity(intentmain);
finish();
}
/*Gson gson = new Gson();
Map retMap = gson.fromJson(jsonString,
new TypeToken