I've seen a number of questions on here already here and here but still not able to the following working.
For either of these responses which are in ex.Message:
Response 1
[
{
"validationErrorType": "WrongType",
"message": "Validation error of type WrongType",
"errorType": "ValidationError"
}
]
Response 2
[
{
"message": "Validation error of type WrongType:",
"errorType": "ValidationError"
}
]
I am trying to dynamically parse this as follows:
JArray parsedJObject = JArray.Parse(ex.Message);
JSchema oldSchema = JSchema.Parse(@"
{
'type': 'array',
'properties': {
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false
}");
JSchema graphQlSchema = JSchema.Parse(@"
{
'type': 'array',
'properties': {
'validationErrorType': {'type': 'string'},
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false
}");
if (parsedJObject.IsValid(oldSchema)) // IsValid - 1
{
// Do stuff
}
else if (parsedJObject.IsValid(graphQlSchema)) // IsValid - 2
{
// Do stuff
}
However both IsValid() calls return true for either response. What am I doing wrong here?
For response 1, I'm expecting IsValid - 1
to return true
and IsValid - 2
to return false
And for response 2, I'm expecting IsValid - 1
to return false
and IsValid - 2
to return true
Update
Following the suggestions by David Kujawski and dbc to loop through the JArray and add the required
attribute I've made progress.
My updated code is below but still struggling with validating a schema with a nested locations
object.
Response
[
{
"validationErrorType": "WrongType",
"locations": [
{
"line": 4,
"column": 1
}
],
"message": "Validation error of type WrongType",
"errorType": "ValidationError"
}
]
Schema Definition:
JSchema graphQlSchema = JSchema.Parse(@"
{
'type': 'object',
'properties':
{
'validationErrorType': {'type': 'string'},
'locations':
{
'type': 'object',
'properties':
{
'line': {'type': 'string'},
'column': {'type': 'string'}
}
},
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false,
'required': ['message', 'errorType', 'validationErrorType', 'locations']
}");
Parsing response
JArray parsedJObject = JArray.Parse(ex.Message);
foreach (JToken child in parsedJObject.Children())
{
if (child.IsValid(graphQlSchema)) // Not resolving to true
{
var graphQlSchemaDef = new[]
{
new
{
validationErrorType = string.Empty,
locations = new
{
line = string.Empty,
column = string.Empty
},
message = string.Empty,
errorType = string.Empty
}
};
var exceptionMessages = JsonConvert.DeserializeAnonymousType(ex.Message, graphQlSchemaDef);
foreach (var message in exceptionMessages)
{
// Do stuff
}
}
}