0

I have two sample of JSON Response by Expedia Hotel REST API

Sample -1

{
    "Room": {
        "numberOfAdults": 2,
        "numberOfChildren": 1,
        "childAges": 1,
        "rateKey": "82b0b5af-9f9a-41d5-bf39-c262d66aed19"
    }
}

Sample -2

{
    "Room": [
        {
            "numberOfAdults": 2,
            "numberOfChildren": 1,
            "childAges": 1,
            "rateKey": "82b0b5af-9f9a-41d5-bf39-c262d66aed19"
        },
        {
            "numberOfAdults": 2,
            "numberOfChildren": 1,
            "childAges": 1,
            "rateKey": "82b0b5af-9f9a-41d5-bf39-c262d66aed19"
        }
    ]
}

So sample -1 is Single Room Object and Sample -2 is array of Object and I want to store this JSON Response to our java POJO and This is way that I tried.

POJO-1

import java.util.List;

public class RoomGroup{
    private List<Room> Room;

    public List<Room> getRoom(){
        return this.Room;
    }
    public void setRoom(List<Room> room){
        this.Room = Room;
    }
}

This Pojo is working fine for Sample-2 but for sample -1 GSON is showing exception like "Excepting Array Object but response was object"

POJO-2

  public class RoomGroup{
    private Room Room;

    public Room getRoom(){
        return this.Room;
    }
    public void setRoom(Room room){
        this.Room = Room;
    }
}  

So this pojo is working fine for sample -1 but for Sample -2 Gson is showing exception like "Excepting Object but was Array of Object" .

I am using spring rest template along with Gson.

RestTemplate restTemplate = new RestTemplate();
  restTemplate.getForObject(sb.toString(),String.class,MediaType.APPLICATION_JSON);

  Gson gson= new Gson(); 
  InitialHotelRoomAvailbility availbilityInfo = fromJson(hotelAvailibilityInfoStringResponse, InitialHotelRoomAvailbility.class); 

So please any one let me know where I am doing mistake for creating java Pojo for these json response.

your help would be appreciated.

Thank you in Advance.

user3069091
  • 71
  • 1
  • 2
  • 10

1 Answers1

0

In JSON, an element wrapped in {} is a JSON object. An element wrapped in [] is a JSON array.

Your sample -1 is a JSON object, that contains a JSON object named Room, that contains a bunch of JSON primitives (strings and numbers).

Your sample -2 is a JSON object, that contains a JSON array named Room, that contains a bunch of JSON objects with a bunch of JSON primitives.

You will need to deserialize the JSON element named Room differently, sample -1 as Room and sample -2 as List<Room> .

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724