Getting JSON from RetrofitError object using Retrofit

后端 未结 9 1740
Happy的楠姐
Happy的楠姐 2020-12-24 01:39

I am using the Retrofit library to do REST calls to a service I am using.

If I make an API call to my service and have a failure, the service returns a bit of JSON

9条回答
  •  一生所求
    2020-12-24 01:59

    Two-Liner with getBodyAs to get a JSON Object.

    JsonObject responseAsJson = (JsonObject) retrofitError.getBodyAs(JsonElement.class);
    
    String message = responseAsJson.get("error").getAsString(); //=> "Username already in use"
    

    Confirmed working in Retrofit 1.x. Not sure what changes are required for Retrofit 2.x.

提交回复
热议问题