3

I'm having an issue with an API that could return either ARRAY or OBJECT, below are the data format:

OBJECT format:

{
    "info":"no package",
    "time":"04-20-2016"
}

ARRAY format:

[
   {
      "package_id":"1234",
      "from":"CA",
      "arrive_time":"05-02-2016"
   },
   {
      "package_id":"4567",
      "from":"DE",
      "arrive_time":"05-04-2016"
   }
]

After checked some posts (Custom converter for Retrofit 2, Multiple converters with Retrofit 2), I have some clue the it should be dealed with Gson deserializer or Custom converter, but my case seems a little different. Then how to deal with it? Thanks in advance.

Update: change the example to a more proper one.

Twisted Lullaby
  • 551
  • 1
  • 8
  • 20
  • 1
    Possible duplicate of [Handle different JSON response types from same endpoint in RetroFit](http://stackoverflow.com/questions/35381646/handle-different-json-response-types-from-same-endpoint-in-retrofit) – Tom Sabel Apr 19 '16 at 10:18
  • @Exaqt yeah, that is one solution, but in my opinion using custom Converter or TypeAdater would be more decent. – Twisted Lullaby Apr 19 '16 at 13:46
  • https://stackoverflow.com/a/48263762/5304075 answer could help you – Arul Nov 03 '19 at 10:09
  • Usually this is an example for a terribly designed API contract. If one can have any impact on the endpoint, it's better to convince the developers to change it to something more consistent. – dephinera Mar 28 '20 at 18:10

1 Answers1

0

Chaosphinx

I agree your problem is different from this posts that you have referenced.

Your first Json has informations about and exception in your request and the second one is returned when your request was successful. I can suggest you to check the Response HTTP Code before to convert the Json. If the code is 202 (java.net.HttpURLConnection.HTTP_OK), is because you request was successful and the API will return the second Json, that you will convert to object. If the code is something else is because an exception has happened and you should deal with it in a different way.

An example:

            Response<List<MyObject>> response = myResource.myMethod().execute();
            switch (response.code()) {
                case HTTP_OK:
                    return response.body();
                default:
                    //OPS! Request has failed!
            }
Tássio Auad
  • 111
  • 5
  • Hi, in fact, it's not an exception but a successful return. The API is just designed this way (not by me). I've changed the example to a more proper one. I think it's very similar to the links I referenced, I just can't figure it out. – Twisted Lullaby Apr 19 '16 at 16:06
  • So, the ("info":"no package") doens't mean that your request has had as response a NO_CONTENT(code 204)? – Tássio Auad Apr 19 '16 at 17:40
  • 1
    RIght, it's a normal HTTP_OK response. – Twisted Lullaby Apr 20 '16 at 03:03