Click or drag to resize
Json.NET

Validate with validation error messages

 

This sample validates a JObject using the IsValid(JToken, JsonSchema) extension method and returns error messages.

Caution note Caution

Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.

Sample
Usage
string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {
      'type': 'array',
      'items': {'type':'string'}
    }
  }
}";

JsonSchema schema = JsonSchema.Parse(schemaJson);

JObject person = JObject.Parse(@"{
  'name': null,
  'hobbies': ['Invalid content', 0.123456789]
}");

IList<string> messages;
bool valid = person.IsValid(schema, out messages);

Console.WriteLine(valid);
// false

foreach (string message in messages)
{
    Console.WriteLine(message);
}
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.