Getting JSON from RetrofitError object using Retrofit

后端 未结 9 1814
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 02:10

    I compile many answer and wrote some code to achieve something nicer :

    {
        "errors": {
            "email": [
                "Email not valid.",
                "Unable to find the user toto@toto.fr."
            ]
        }
    }
    

    I take all item in 'email' and display them concatained with Guava Joiner:

    String json =  new String(((TypedByteArray)error.getResponse()
        .getBody()).getBytes());
    
    Map map = new Gson().fromJson(
        json, new TypeToken>>>() {}.getType());
    
    try {
        List errorsEmail = 
            (List) ((Map)map.get("errors")).get("email");
        Toast.makeText(getApplicationContext(), Joiner.on("\n")
            .join(errorsEmail), Toast.LENGTH_SHORT).show();
    } catch(Exception e){
        Log.e(Constants.TAG, e.getMessage());
    }
    

提交回复
热议问题