2

I receive some jsons that are supposed to represent a legal object of some class. I wish to validate this is indeed so. So I deserialized the strings to see if this succeeds. This is very time consuming as the strings gets very large in some cases and there are many of them. I am therefore looking for a different approach.

I thought of creating a regExp from the class's definition and check that the jsons I receive are compatible. Is there a way to generate a regExp from a C# class?

Any other suggestions will help as well.

Thanks

  • The language of json strings is not regular neither linear. But even with the advanced features of regex, it is not possible to validate json with it. However, you could create a pattern from some classes, but not in general. – ZorgoZ Apr 04 '19 at 19:31
  • Have you looked into [JSON Schema](https://json-schema.org)? – Aman Agnihotri Apr 04 '19 at 19:33
  • Check [this](https://stackoverflow.com/q/55420732/4685428) question – Aleks Andreev Apr 04 '19 at 19:35

1 Answers1

0

Use JSON schema validator by newtonsoft , more details here


        public class JsonSchemaController : ApiController
    {
        [HttpPost]
        [Route("api/jsonschema/validate")]
        public ValidateResponse Valiate(ValidateRequest request)
        {
            // load schema
            JSchema schema = JSchema.Parse(request.Schema);
            JToken json = JToken.Parse(request.Json);

            // validate json
            IList<ValidationError> errors;
            bool valid = json.IsValid(schema, out errors);

            // return error messages and line info to the browser
            return new ValidateResponse
            {
                Valid = valid,
                Errors = errors
            };
        }
    }

    public class ValidateRequest
    {
        public string Json { get; set; }
        public string Schema { get; set; }
    }

    public class ValidateResponse
    {
        public bool Valid { get; set; }
        public IList<ValidationError> Errors { get; set; }
    }

Ali Alp
  • 691
  • 7
  • 10