Tell me, how best to process a request using Retrofit 2, if it can come to the answer of a different structure?
Here is a specific example - on a POST request.

@POST("Authorization/Login") Call<Authorization> authorization(@Header("Content-Type") String contentType, @Body JSONLoginPassword jsonLoginPassword); 

A JSON response comes with two parameters: status and data , and if "status":"ok" , then data is a string of characters (a token, for example, "data":"xxx308f9-04xx3a-4xxxd-b6ba-89xx9c8xxxx" ). And if "status":"error" , then data for example could be such "data":{"code":"wrong-login-or-password","message":"Неверный логин или пароль"} , that is, already not a string, but a set of name: value pairs. Accordingly, if I specify one of the response structures, and another one arrives, then my authorization method falls into onFailure with the error com.google.gson.JsonSyntaxException .
Does Retrofit 2 have tools for creating an alternative response structure, and if not, how can this problem be solved?

    2 answers 2

    Honestly, even though I did a lot with this library, I cannot tell you with certainty whether there are any mechanisms for creating an alternative response structure. What I can offer you, you get a response from the server, which you can understand if the if (response.isSuccessful()) condition is true. You just need to create several methods that will be called depending on what value the status variable has. Here, for example, your status is ok, then we call the method for pulling out a token, if the status is error then we call the method that pulls either the message from the answer, or without steaming at once we deduce some kind of condition that you have a problem.

    This is just my personal opinion, based on short practice with this library, maybe someone will have a better solution, but I would do so. Good luck :)

    • I can’t check status if the answer came from a different structure, because I fall in onFailure . That's the problem. - Sergey Garbuz
    • I imagine it like this: it is necessary that only the status field is processed and, depending on its value, this or that model is used for the data field, but I don’t know how to implement it yet. - Sergey Garbuz
    • @SergeyGarbuz, yes you absolutely correctly think that the behavior of your program depends only on the status variable. But I think that all the same you will need to also process the incoming data value. In the model class, you need to make status retrieval, but then you need to work with the data. - Andrew Goroshko
    • If you are given an exhaustive answer, mark it as accepted - Andrew Goroshko

    Brought myself to the solution of the problem :) data made of Object type, and then in onResponse , depending on the status value, I either immediately get a token, like response.body().getData().toString() , or convert Object to JSONObject and getString method I get the necessary fields.