Click or drag to resize
Json.NET Schema

Validating JSON

 

With Json.NET Schema you can simply validate JSON in LINQ to JSON objects using the IsValid method. In more advanced scenarios you can validate JSON as you read and write it using JSchemaValidatingReader and JSchemaValidatingWriter

Validating with JSON Schema

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema.

Validate JSON with IsValid
string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties': {
    'name': {'type': 'string'},
    'hobbies': {
      'type': 'array',
      'items': {'type': 'string'}
    }
  }
}";

JSchema schema = JSchema.Parse(schemaJson);

JObject person = JObject.Parse(@"{
  'name': 'James',
  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
// true

To get validation error messages use the IsValid(JToken, JSchema, IListString) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

Validate JSON with IsValid
JSchema schema = JSchema.Parse(schemaJson);

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

IList<string> messages;
bool valid = person.IsValid(schema, out messages);
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Number. Line 3, position 51.
Detailed Validation Information

Detailed validation error information is accessable on ValidationError. It provides the line number, position and path of where the error occurred in the JSON document, the JSchema that failed validation, and any child errors that occured.

IsValid(JToken, JSchema, IListValidationError) and ValidationError both provide ValidationError for any errors.

Detailed validation information with ValidationError
string schemaJson = @"{
  'description': 'Collection of non-primary colors',
  'type': 'array',
  'items': {
    'allOf': [ { '$ref': '#/definitions/hexColor' } ],
    'not': {
      'enum': ['#FF0000','#00FF00','#0000FF']
    }
  },
  'definitions': {
    'hexColor': {
      'type': 'string',
      'pattern': '^#[A-Fa-f0-9]{6}$'
    }
  }
}";

JSchema schema = JSchema.Parse(schemaJson);

JArray colors = JArray.Parse(@"[
  '#DAA520', // goldenrod
  '#FF69B4', // hot pink
  '#0000FF', // blue
  'Black'
]");

IList<ValidationError> errors;
bool valid = colors.IsValid(schema, out errors);
// Message - JSON is valid against schema from 'not'. Path '[2]', line 4, position 24.
// SchemaId - #/items/0

// Message - JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0. Path '[3]', line 5, position 22.
// SchemaId - #/items/0
//   Message - String 'Black' does not match regex pattern '^#[A-Fa-f0-9]{6}$'. Path '[3]', line 5, position 22.
//   SchemaId - #/definitions/hexColor
Validating when reading JSON

Internally IsValid uses JSchemaValidatingReader to perform the JSON Schema validation. To skip the overhead of loading JSON into a JObject/JArray, validating the JSON, and then deserializing the JSON into a class, JSchemaValidatingReader can be used with JsonSerializer to validate JSON while the object is being deserialized.

Validate JSON with JSchemaValidatingReader
string json = @"{
  'name': 'James',
  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}";

JsonTextReader reader = new JsonTextReader(new StringReader(json));

JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
validatingReader.Schema = JSchema.Parse(schemaJson);

IList<string> messages = new List<string>();
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);

JsonSerializer serializer = new JsonSerializer();
Person p = serializer.Deserialize<Person>(validatingReader);
Validating when writing JSON

JSON can also be validated while writing JSON with JSchemaValidatingWriter.

Validate JSON with JSchemaValidatingWriter
Person person = new Person
{
    Name = "James",
    Hobbies = new List<string>
    {
        ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
    }
};

StringWriter stringWriter = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(stringWriter);

JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
validatingWriter.Schema = JSchema.Parse(schemaJson);

IList<string> messages = new List<string>();
validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);

JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(validatingWriter, person);
See Also