Hi,
I’m using NewtonSoft library to validate input json data, in my rest routes before going futher down the code, so i dont have to bother with validation.
So i create a JSon schema, and when the data are sent to one of my route, i make sure the input json is valid. If not, i exit the route and return an array of the errors present in the input JSON.
Maybe this could be a good idea to implement this idea natively when a route has a POST/PUT/DELETE method, we could imagine a parameter -JsonSchema
pointing to a valid schema file …
This is how i do it:
Before starting UD i import the DLL and create a custom class
$NewtonsoftJsonPath = "c:\Common\NewtonSoft\Newtonsoft.Json.dll"
$NewtonsoftJsonSchemaPath = "c:\Common\NewtonSoft\Newtonsoft.Json.Schema.dll"
Add-Type -Path $NewtonsoftJsonPath
Add-Type -Path $NewtonsoftJsonSchemaPath
$source= @"
public class Jsonvalidation
{
public static System.Collections.Generic.IList<string> IsValid (string jsonFile, string schemaFile)
{
var schema = System.IO.File.ReadAllText(schemaFile);
var jToken = Newtonsoft.Json.Linq.JToken.Parse(jsonFile);
var jSchema = Newtonsoft.Json.Schema.JSchema.Parse(schema);
System.Collections.Generic.IList<string> messages;
Newtonsoft.Json.Schema.SchemaExtensions.IsValid(jToken, jSchema, out messages);
return messages;
}
}
"@
And you can call it like that [JsonValidation]::isValid($body,"pathtomyschema")
If there are errors, an array of error is returned, and i output it, then exit my route.