I have a web call that returns JSON.
The response call can either be an array or an object.
I want to validate if the response is the array.
I am using JSON.NET.
Here is my schema:
string planElevationListSchema = @"{
'description': 'Plan elevation object array',
'type': 'array',
'items': {
'type': 'object',
'properties': {
'COMMUNITYNUMBER': { 'type': 'string' },
'PLANNUMBER': { 'type': 'string' },
'ELEVATION': { 'type': 'string' }
}
}
}";
Here is my code:
JsonSchema schema = JsonSchema.Parse(planElevationListSchema);
JArray planElevationList = JArray.Parse(responseFromServer.ToString());
bool isValid = planElevationList.IsValid(schema);
If the JSON object is returned, I get an
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
Do I need to wrap my code in a try/catch or make another schema for the object?
Whichever I use to parse the response could throw an exception.
How to handle?
Added Here is what the returned object looks like:
"{ \"Error\": \"No Active Plan/Elevations for 44003150099\" }"
Here is the valid object array returned:
"[{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1700\",\"ELEVATION\":\"A\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1700\",\"ELEVATION\":\"B\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1700\",\"ELEVATION\":\"C\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1700\",\"ELEVATION\":\"D\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1800\",\"ELEVATION\":\"A\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1800\",\"ELEVATION\":\"B\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1800\",\"ELEVATION\":\"C\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1800\",\"ELEVATION\":\"D\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1890\",\"ELEVATION\":\"A\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1890\",\"ELEVATION\":\"B\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1890\",\"ELEVATION\":\"C\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"1890\",\"ELEVATION\":\"D\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2270\",\"ELEVATION\":\"A\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2270\",\"ELEVATION\":\"B\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2270\",\"ELEVATION\":\"C\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2270\",\"ELEVATION\":\"D\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2440\",\"ELEVATION\":\"A\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2440\",\"ELEVATION\":\"B\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2440\",\"ELEVATION\":\"C\"},{\"COMMUNITYNUMBER\":\"44002050000\",\"PLANNUMBER\":\"2440\",\"ELEVATION\":\"D\"}]"