Validate JSON against JSON Schema C#
I think that you just need to add
'additionalProperties': false
to your schema. This will stop unknown properties being provided.
So now your results will be:- True, False, False
test code....
void Main()
{
var schema = JsonSchema.Parse(
@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
},
'additionalProperties': false
}");
IsValid(JObject.Parse(
@"{
'name': 'James',
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
IsValid(JObject.Parse(
@"{
'surname': 2,
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
IsValid(JObject.Parse(
@"{
'name': 2,
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
}
public bool IsValid(JObject obj, JsonSchema schema)
{
return obj.IsValid(schema);
}
output :-
True
False
False
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:-
Property 'surname' has not been defined and the schema does not allow additional properties. Line 2, position 19.
Required properties are missing from object: name.
Invalid type. Expected String but got Integer. Line 2, position 18.
Validate Json schema C#
The reason you cannot pass the validation test is because your json data is actually an array, but not an single object.
If you assume your input data is an array, you may modify the code like:
public static bool ValidJson(string jsonData)
{
string myJson = @"{
'description': 'rehber',
'type': 'object',
'properties':
{
'isim': {'type':'string', 'required': true },
'tel': {'type':'string','required': true},
},
'additionalProperties': false
}";
JsonSchema schema = JsonSchema.Parse(myJson);
JArray jArray = JArray.Parse(jsonData);
foreach( var jToken in jArray)
{
if ( !jToken.IsValid(schema))
{
return false;
}
}
return true;
}
Please also noted that the JsonSchema & isValid method are deprecated, Newtonsoft has a new project, please check https://www.newtonsoft.com/jsonschema .
Validating JSON with JSON Schema in C# using Newtonsoft
JsonSchema
is deprecated, and has moved to a separate package: Newtonsoft.Json.Schema. Using this package, I was able to validate your JSON against your schema (I did remove the outer schema
element, as it is actually invalid, and causes schema to not validate properly - I think you might've had it in there because the old JsonSchema
class could not parse the schema otherwise!), and get error messages if I changed the JSON to an invalid shape, removed required elements, or changed data to invalid types:
string data = File.ReadAllText("data.json");
string schema = File.ReadAllText("data.schema.json");
var model = JObject.Parse(data);
var json_schema = JSchema.Parse(schema);
IList<string> messages;
bool valid = model.IsValid(json_schema, out messages); // properly validates
I am using .NET Core 2.2, Newtonsoft.Json 12.0.2, and Newtonsoft.Json.Schema 3.0.11, just in case it matters. Please note, the Newtonsoft.Json.Schema package has limitations for commercial use - check licensing!
Related Topics
Circular Reference Causing Stack Overflow with Automapper
How to Convert Namevaluecollection to JSON String
Different Forms of the Wcf Service Contract Interface
Datagridview Changing Cell Background Color
Webdriver How to Wait Until the Element Is Clickable in Webdriver C#
Parsing HTML to Get Content Using C#
Using Custom Colored Cursors in a C# Windows Application
Expose and Raise Event of a Child Control in a Usercontrol in C#
Why Does the Linq Cast<> Helper Not Work with the Implicit Cast Operator
Detect Windows Font Size (100%, 125%, and 150%)
C# Code to Linkify Urls in a String
What's the Max Items in a List<T>