0

I need to validate JSON against a schema like:

bool isValid = SomeJsonSchemaValidator(responseContentInJsonFormat, jsonSchema);

Does anyone know of a .Net Nuget package or something that can do this? I know POSTMAN uses TinyValidator. But I need to do this from C# NUnit Tests.

Sam
  • 4,766
  • 11
  • 50
  • 76

1 Answers1

0

It can be done with Json.NET :

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': 'James',
  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");

bool valid = person.IsValid(schema);

Use this if you need see the error messages:

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

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

Source: http://www.newtonsoft.com/json/help/html/JsonSchema.htm

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44