retrofit中errorbody的读取

在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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值