S
S
Stepan2021-02-11 20:30:46
Java
Stepan, 2021-02-11 20:30:46

Retrofit: what to do when the structure of the server response changes?

Hey!

I understand with API, the detailed description to which is not present.
For example, a GET request to the server: _https:_//server.net/getdetails/?ctn=4950000001
If everything is OK, a response with a 200 code will be returned:

  • if the number was not transferred between operators:

{"code": "495", "num": "0000001", "full_num": "4950000001", "operator": "МГТС", "region": "г. Москва"}

  • if there was a change of operator with the preservation of the number:

{"code": "900", "num": "5555555", "full_num": "9005555555", "operator": "ВымпелКом", "old_operator": "СИМ ТЕЛЕКОМ", "region": "г. Москва * Московская область"}
, the old_operator parameter is added .

If something is wrong with the input data, a response with a 404 code will be returned.
The response body will be:
  • This:
{"info": "Неверный формат номера: 49500000", "example": ["+74959898533", "74959898533", "84959898533", "4959898533"]}

  • This:
{"info": "Номер не найден. Проверьте код города: 000", "example": ["3XX", "4XX", "8XX", "9XX"]}

  • or that:
{"info": "Неверный формат запроса, ctn обязательный параметр", "example": "https://server.net/getdetails/?ctn=+74959898533"}


How to handle server response with Retrofit? Is it possible?
As far as I understand, it (Retrofit) creates an object from the response, which I can then work with.
What to do if both the server response itself (code, content) and the format of the correct JSON response change?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-02-11
@steff

Yes, you can live with it. Retrofit itself does not convert the response to json, for this it is given addConverterFactory(factory). You need to write a custom adapter for the json conversion library that you use (examples about Gson ). From the response, you will have to understand what exactly came and return the corresponding object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question