Android : Parsing JSON to Object using GSON independent of list or object

on Saturday, November 1, 2014


I am implementing an API from Rejseplanen.dk where I can receive either a list of someting or an object. The problem is that I don't know when I will be receiving what. Here is a small example of what I can receive:


Example here I will receive a list: (full request:



"JourneyName": [
{
"name": "IC 865",
"routeIdxFrom": "0",
"routeIdxTo": "29"
},
{
"name": "IC 865",
"routeIdxFrom": "29",
"routeIdxTo": "37"
}
],
"JourneyType": [
{
"type": "IC",
"routeIdxFrom": "0",
"routeIdxTo": "29"
},
{
"type": "IC",
"routeIdxFrom": "29",
"routeIdxTo": "37"
}
],


Example with an object:



"JourneyName": {
"name": "Bybus 5",
"routeIdxFrom": "0",
"routeIdxTo": "41"
},
"JourneyType": {
"type": "TB",
"routeIdxFrom": "0",
"routeIdxTo": "41"
},


I am using GSON to parse the received JSON string into a JAVA Object like this:



Gson gson = new GsonBuilder().setPrettyPrinting().create();
MyClass myClass = gson.fromJson(getResponse(), MyClass.class);


How will I be able to make this convertion? I thought that I could simply treat the object as a list but if I do I will get this exception:



com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 258 column 18 path $.JourneyDetail.JourneyName

0 comments:

Post a Comment