Validating JSON (2024)

Validating JSON (1)

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 JSON (2)Validating with JSON Schema

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

Validate JSON with IsValid

Copy

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 theIsValid(JToken, JSchema, IListString)orValidate(JToken, JSchema, SchemaValidationEventHandler)overloads.

Validate JSON with IsValid

Copy

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.

Validating JSON (3)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 JSON (4)Validating when reading JSON

Internally IsValid uses JSchemaValidatingReaderto perform the JSON Schema validation. To skip the overhead of loading JSON into a JObject/JArray, validatingthe 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

Copy

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 JSON (5)Validating when writing JSON

JSON can also be validated while writing JSON with JSchemaValidatingWriter.

Validate JSON with JSchemaValidatingWriter

Copy

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);

Validating JSON (6)See Also

Validating JSON (2024)
Top Articles
Benefits Contacts: Information lines, Phone Numbers and Websites for Medical and Other Benefits Help
How to respond when you can’t answer a question - PR Daily
Walgreens Boots Alliance, Inc. (WBA) Stock Price, News, Quote & History - Yahoo Finance
Places 5 Hours Away From Me
Craigslist Cars And Trucks For Sale By Owner Indianapolis
1movierulzhd.fun Reviews | scam, legit or safe check | Scamadviser
Mail Healthcare Uiowa
Tanger Outlets Sevierville Directory Map
2021 Lexus IS for sale - Richardson, TX - craigslist
Costco Gas Foster City
4156303136
Peraton Sso
Kitty Piggy Ssbbw
Po Box 35691 Canton Oh
Trac Cbna
Where to Find Scavs in Customs in Escape from Tarkov
Alfie Liebel
Craigslist Southern Oregon Coast
Rufus Benton "Bent" Moulds Jr. Obituary 2024 - Webb & Stephens Funeral Homes
Tripadvisor Napa Restaurants
Is Windbound Multiplayer
Scream Queens Parents Guide
Baja Boats For Sale On Craigslist
Piri Leaked
Cb2 South Coast Plaza
Culver's.comsummerofsmiles
Hrconnect Kp Login
Bfsfcu Truecar
Barbie Showtimes Near Lucas Cinemas Albertville
Baldur's Gate 3 Dislocated Shoulder
Sitting Human Silhouette Demonologist
Weekly Math Review Q4 3
Final Exam Schedule Liberty University
R&J Travel And Tours Calendar
Reborn Rich Ep 12 Eng Sub
Gold Nugget at the Golden Nugget
Sunrise Garden Beach Resort - Select Hurghada günstig buchen | billareisen.at
Housing Intranet Unt
Barstool Sports Gif
2132815089
Mitchell Kronish Obituary
30 Years Of Adonis Eng Sub
Swsnj Warehousing Inc
Doe mee met ons loyaliteitsprogramma | Victoria Club
Playboi Carti Heardle
Graduation Requirements
Mcoc Black Panther
Mikayla Campinos Alive Or Dead
28 Mm Zwart Spaanplaat Gemelamineerd (U999 ST9 Matte | RAL9005) Op Maat | Zagen Op Mm + ABS Kantenband
Uncle Pete's Wheeling Wv Menu
91 East Freeway Accident Today 2022
Worlds Hardest Game Tyrone
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 5753

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.