APis Retrofit GSON: Datatypes changing all the time

Viewed 43

I am using Retrofit with GSON for an app for a client, and I am having some trouble with some of my client APIs and I need to workaround this problem.

Let's say i have an API which gives me telephones:

{
  "telephones": [
  {"phoneNumber": "1234567890"},
  {"phoneNumber": "2123456789"}
  ]
}

But my client decided if there is only one telephone i am sending you:

{
   "telephones": 
   {"phoneNumber": "1234567890"}
}

And when there is no telephone:

{
   "telephones": "No telephone Available"
}

Is there any workaround i can make with Kotlin to solve this datatype problem? In iOS I could force them reimplementing the Coding method and force them to always have an array. Is it possible to do something similar in Kotlin?

This is a small example, since the original answer has between 600 and 1300 lines of JSON data.

1 Answers

This might work.

I have done this in many places in my app. So, the first thing, let's say you receive multiple different telephone numbers in one JSON file and might look something like this.

  • install a plugin call JSON to Kotlin Class
  • once done, make a new file using "Kotlin data class file from JSON"
  • the plugin for me creates automatically appropriate files.
  • then I use the main file to capture the data, this has worked for me almost everytime.

And yes, my other answer was if you are doing everything manually, while retrieving the data make a data class such as: This is just for explanation purposes.

//lets say your json looks something like this
"records": [
        {
            "id": "1",
            "telephones": [
      {"phoneNumber": "1234567890"},
      {"phoneNumber": "2123456789"}
      ]
        },
        {
            "id": "2",
            "telephones": 
      {"phoneNumber": "1234567890"}
        },
        {
            "id": "3",
            "telephones": "No telephone Available"
        }
]

my example code would look something like this.

data class records(
//some id 
val id: Int,
var telephones: List<Long>
)

so, now check inside telephones how many elements are there and add them to the list one by one.

Related