using Newtonsoft.Json; using Newtonsoft.Json.Schema; using System.IO; string json = "{\"name\": \"John\", \"age\": 30}"; string schemaJson = "{\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}, \"age\": {\"type\": \"integer\"}}}"; JsonSchema schema = JsonSchema.Parse(schemaJson); JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonValidatingReader validatingReader = new JsonValidatingReader(reader); validatingReader.Schema = schema; while (validatingReader.Read()) {} if (validatingReader.ValidationErrors.Count > 0) { Console.WriteLine("JSON is not valid."); } else { Console.WriteLine("JSON is valid."); }
using Newtonsoft.Json; using Newtonsoft.Json.Schema; using System.IO; string json = "[{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}]"; string schemaJson = "{\"type\": \"array\", \"items\": {\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}, \"age\": {\"type\": \"integer\"}}}}"; JsonSchema schema = JsonSchema.Parse(schemaJson); JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonValidatingReader validatingReader = new JsonValidatingReader(reader); validatingReader.Schema = schema; while (validatingReader.Read()) {} if (validatingReader.ValidationErrors.Count > 0) { Console.WriteLine("JSON is not valid."); } else { Console.WriteLine("JSON is valid."); }These examples use the Newtonsoft.Json package library, specifically the JsonValidatingReader class in the Newtonsoft.Json.Schema namespace.