0

I am making a REST request that returns json object RoomGroup. Depending on the parameters in the request it is either returning one Room object or list of Room objects. How to write gson code that can handle both the responses and convert to java correctly?

Ex:

RoomGroup: {
    Room: {
        numberOfAdults: 2
        numberOfChildren: 0
    }
}

OR

RoomGroup: {
    Room: [2]
    0:  {
        numberOfAdults: 2
        numberOfChildren: 0
    }
    1:  {
        numberOfAdults: 1
        numberOfChildren: 0
    }
}
Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
Santosh N
  • 1
  • 1
  • Specify that it should always be an array. Everyone's life will be easier. Avoid complicating the API with multiple flavours of the same endpoint. Make a choice and stick to it. – Bohemian Oct 13 '14 at 07:20

1 Answers1

0

I would return an array of Rooms, each one identified by roomNumber.

Rooms: [
    {
        roomNumber: 313
        numberOfAdults: 2
        numberOfChildren: 0
    },
    {
        roomNumber: 310
        numberOfAdults: 1
        numberOfChildren: 0
    }
]

Then, extract your JsonArray Rooms and map to Java class with Gson.

gasparms
  • 3,336
  • 22
  • 26
  • Since I am invoking the REST service provided by Third Party I cannot modify the response that is coming.I am trying to convert the json response received into java. Please let me know how I can do that. – Santosh N Oct 13 '14 at 23:27