You'll need to load a JSchema object using the code you've already seen. NET Framework object with validation done automatically as part of the conversion. With a little more code, you can convert your JSON object into a. Using NewtonSoft's tools like this still, however, leaves you with a JSON document to parse into. In C#, the second parameter that holds the error messages must be marked as out. '.assemble error message collection to return to the client. Typical code using the IsValid method would look like this: That collection will be populated with any error messages that are found. Regardless of how you load the two objects, to check that the JSON document is valid against the schema, you call the JObject's IsValid method passing the JSchema object and a collection declared as an IList of String.
In a Web service, the most likely combination is that you'll read your schema from a file but will be accepting your JSON document as a parameter to an ASP.NET Web API method. Jo = JObject.Parse(File.ReadAllText("CustomerRequest.json")) Js = JSchema.Parse(File.ReadAllText("RequestCustomerSchema.json")) The simplest way to load your JSchema and JObject classes from files is to use the File object's ReadAllText method, like this: I suspect that this code isn't reasonable, at least for processing the schema - you're probably keeping your schema in a file.
The code assumes that the schema is in a string variable called jsonSchema and the actual JSON is in a string variable called jsonInput: You can use NewtonSoft's JSchema and JObject classes to parse JSON strings and then check to see if the JSON string is valid against the schema. NewtonSoft's package is free as long as you're doing fewer than 1,000 validations per hour - if you think you'll be doing more than that, you should check out their pricing.
The package contains two objects that you can use for validation: JsonSchema (which is deprecated) and the newer, cooler JSchema (which is what you should use).
I also showed how to use that schema to provide support for developers creating JSON documents in Visual Studio (or any other editor that supports JSON Schemas).īut you can also use your JSON schemas at run time to validate JSON files or messages, ensuring your code doesn't try to process something that isn't correctly formatted.Ī number of packages support JSON validation with schemas, but is easily available through NuGet (if you're working in ASP.NET Core there's currently a prerelease version available). In an earlier column, I showed how to create a JSON schema that describes the format of a valid JSON document.