Reputation: 35
I have the following json returned by web api but I'm getting the following error when trying to parse it: this is not a json array.
{
"$id": "1",
"updateTime": "2013-12-10T12:28:26.6533786+00:00",
"user": {
"$id": "2",
"CompanyID": 1,
"username": "test",
"Firstname": "test",
"Lastname": "ing"
},
"Vehicles": {
"$id": "3",
"$values": [
{
"$id": "4",
"VehicleID": 1,
"CompanyID": 1,
"VehicleReg": "123",
"VehicleTypeID": 1,
"VehicleDescription": ""
},
{
"$id": "5",
"VehicleID": 4,
"CompanyID": 1,
"VehicleReg": "456",
"VehicleTypeID": 2,
"VehicleDescription": ""
},
{
"$id": "6",
"VehicleID": 7,
"CompanyID": 1,
"VehicleReg": "789",
"VehicleTypeID": 3,
"VehicleDescription": ""
}
]
},
"VehicleTypes": {
"$id": "7",
"$values": [
{
"$id": "8",
"VehicleTypeID": 1,
"VehicleType": "First Test Type",
"CompanyID": 1
},
{
"$id": "9",
"VehicleTypeID": 2,
"VehicleType": "Second Test Type",
"CompanyID": 1
},
{
"$id": "10",
"VehicleTypeID": 3,
"VehicleType": "Third Test Type",
"CompanyID": 1
}
]
},
"Questions": {
"$id": "11",
"$values": [
{
"$id": "12",
"QuestionID": 1,
"SectionID": 1,
"CompanyID": 1,
"Question": "Question 1"
},
{
"$id": "13",
"QuestionID": 2,
"SectionID": 1,
"CompanyID": 1,
"Question": "Question 2"
},
{
"$id": "14",
"QuestionID": 3,
"SectionID": 1,
"CompanyID": 1,
"Question": "Question 3"
}
]
},
"QuestionSections": {
"$id": "15",
"$values": [
{
"$id": "16",
"SectionID": 1,
"CompanyID": 1,
"SectionName": "Section 1"
}
]
}
}
I have put this through a parser and it does say it's valid json.
I'm trying to parse the Vehicles in the json like so:
Gson gsonv = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = (JsonArray)parser.parse(reader).getAsJsonArray();
ArrayList<VehicleEntity> lcs = new ArrayList<VehicleEntity>();
for(JsonElement obj : Jarray )
{
VehicleEntity v = gsonv.fromJson( obj , VehicleEntity.class);
lcs.add(v);
Log.d(TAG, "Vehicles: " + v.VehicleID);
}
My VehicleEntity matches the properties in the json Vehicles portion.
Am I on the right path here or is it a problem with the json returned by the web api?
Thanks Paul
Upvotes: 0
Views: 1107
Reputation: 3847
The top-level JSON is a JSONObject (surrounded by {}, with keys) not a JSONArray (surrounded by [], basically a list).
It sounds like you're expecting an array of these Objects, but it doesn't look like that's what you're getting.
If you wrap that object in '[' and ']' you'd have an array of length 1, and maybe your code would work.
There are sometimes server settings that send a single Object instead of a JSONArray if there is only 1 element. Maybe that's the case? What if you preform a server query that returns multiple results? Then does your code work?
Upvotes: 1