Is there a way to validate a JSON structure against a JSON schema for that structure? I have looked and found JSON.Net validate but this does not do what I want.
JSON.net does:
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
This validates to true.
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'surname': 2,
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
This also validates to true
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'name': 2,
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
Only this validates to false.
Ideally I would like it to Validate that there are no fields aka name
in there that shouldn't be in there aka surname
.
I think that you just need to add
to your schema. This will stop unknown properties being provided.
So now your results will be:- True, False, False
test code....
output :-
You could also add "required":true to the fields that must be supplied that way you can return a message with details of missing/invalid fields:-
Ok i hope this will help.
This is your schema:
This is your validator:
And how to use is:
If you have any question please ask, hope this helps, please take into consideration that this isn't a complete code without exception handling and such...