I am using GSON to parse JSON data into Java and I am running into the error that is stated in the title. I am working with an API that returns the following JSON data :
{
"STATUS": "SUCCESS",
"NUM_RECORDS": "5",
"MESSAGE": "5 records found",
"AVAILABILITY_UPDATED_TIMESTAMP": "2015-05-03T13:59:08.541-07:00",
"AVAILABILITY_REQUEST_TIMESTAMP": "2015-05-03T13:59:08.490-07:00",
"AVL": [
{
"TYPE": "ON",
"BFID": "205052",
"NAME": "5th St (500-598)",
"RATES": {
"RS": [
{
"BEG": "12:00 AM",
"END": "12:00 PM",
"RATE": "0",
"RQ": "No charge"
},
{
"BEG": "12:00 PM",
"END": "6:00 PM",
"RATE": "5",
"RQ": "Per hour"
},
{
"BEG": "6:00 PM",
"END": "12:00 AM",
"RATE": "0",
"RQ": "No charge"
}
]
},
"PTS": "2",
"LOC": "-122.4002212834,37.7776161738,-122.3989619795,37.7766113458"
},
{
"TYPE": "ON",
"BFID": "205042",
"NAME": "5th St (450-498)",
"RATES": {
"RS": {
"BEG": "12:00 AM",
"END": "12:00 AM",
"RATE": "0",
"RQ": "No charge"
}
},
"PTS": "2",
"LOC": "-122.4015027158,37.7786330718,-122.4005149869,37.7778485214"
},
]
}
I can see where the problem occurs, the RS
field can either contain an array of objects (let's call this object RInfo
) or in some cases it will only contain one of that RInfo
object that is not contained in an array. I think that the error occurs because GSON is looking for an array but found an object. I am unable to change the structure of the JSON file because it was provided by an API.
I am able to parse the information successfully as long as RS
is an array of RInfo
objects but in some cases RS
contains only one RInfo
object so this error occurs.
Is there a way to handle this in GSON?
*Update
I have tried a solution that was linked earlier. Here is what I have from that solution:
class RSDeserializer implements JsonDeserializer<RateInfo[]> {
@Override
public RateInfo[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
if (json instanceof JsonArray) {
System.out.println("fromJson in RSD:" + new Gson().fromJson(json, RateInfo[].class));
return new Gson().fromJson(json, RateInfo[].class);
}
RateInfo rI = context.deserialize(json, RateInfo.class);
return new RateInfo[] { rI };
}
}
I have also created a new GsonBuilder as follows
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(RateInfo[].class, new RSDeserializer());
Gson gson = gsonBuilder.create();
It doesn't seem like the custom deserializer is ever used because the print statement was never printed out in the console. After that I have tried to deserilize the json using MyOBJ info = gson.fromJson(json, MyOBJ.class);
this line gives me the Expected BEGIN_ARRAY but was BEGIN_OBJECT exception.