在retrofit2.0中,返回成功时数据的获取通常都有success和error两种,第一种success的我们就不讨论了,而现在我们看看怎么整理获取errorbody中的json字段:
例子:
Errorbody的json:
{"timestamp":1524031801129,"error":"Precondition Failed","exception":"com.exception.Http412Exception","message":"账户不存在或尚未完善账户信息","path":"/v1/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<String, String> retMap = gson.fromJson(jsonString,
new TypeToken<Map<String, String>>(){}.getType());*/
} catch (IOException e) {
e.printStackTrace();
}