advertise with us

How to Validate JSON Format in C# Using Newtonsoft.Json

Validating the format of JSON data is a critical step when working with APIs, files, or any data input that uses JSON. In this guide, we’ll explore how to validate JSON format in C# using the powerful Newtonsoft.Json library.


Why Validate JSON?

JSON validation ensures that the data follows proper JSON formatting rules, such as correctly nested structures, quoted keys, and valid data types. This helps prevent runtime errors when processing JSON data.


Installing Newtonsoft.Json

First, make sure you have the Newtonsoft.Json library installed in your project. Use the following command in the NuGet Package Manager:

dotnet add package Newtonsoft.Json

Alternatively, you can install it via Visual Studio’s NuGet Package Manager interface.


Simple JSON Validation Example

To validate whether a string is properly formatted JSON, we can attempt to parse it using JsonConvert.DeserializeObject. If the string is invalid, an exception will be thrown.

Code Example

using System;
using Newtonsoft.Json;

class Program
{
static void Main()
{
string json = "{ \"id\": 1, \"name\": \"Product A\" }";

bool isValid = IsValidJson(json);

Console.WriteLine(isValid ? "Valid JSON" : "Invalid JSON");
}

static bool IsValidJson(string json)
{
try
{
JsonConvert.DeserializeObject(json);
return true;
}
catch (JsonException)
{
return false;
}
}
}

Output

Valid JSON

Handling Invalid JSON

If the JSON is invalid, the JsonException provides information about why parsing failed. You can log or display this message for debugging:

static bool IsValidJson(string json, out string errorMessage)
{
try
{
JsonConvert.DeserializeObject(json);
errorMessage = null;
return true;
}
catch (JsonException ex)
{
errorMessage = ex.Message;
return false;
}
}

Usage:

string json = "{ \"id\": 1, \"name\": \"Product A\", }"; // Invalid JSON
if (!IsValidJson(json, out string errorMessage))
{
Console.WriteLine($"Invalid JSON: {errorMessage}");
}

Validating Specific JSON Schema

If you need to ensure that the JSON adheres to a specific schema (e.g., required fields, data types), use a JSON schema validator such as Newtonsoft.Json.Schema. This is a separate NuGet package that works well with Newtonsoft.Json.

Install Json.Schema

dotnet add package Newtonsoft.Json.Schema

Example: Validate Against a Schema

Define the JSON schema:

using Newtonsoft.Json.Schema;

string schemaJson = @"
{
'type': 'object',
'properties': {
'id': { 'type': 'integer' },
'name': { 'type': 'string' }
},
'required': ['id', 'name']
}";

Validate JSON against the schema:

using System;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;

class Program
{
static void Main()
{
string json = "{ \"id\": 1, \"name\": \"Product A\" }";

bool isValid = ValidateJsonAgainstSchema(json, schemaJson, out string errorMessage);

if (isValid)
{
Console.WriteLine("Valid JSON according to schema.");
}
else
{
Console.WriteLine($"Invalid JSON: {errorMessage}");
}
}

static bool ValidateJsonAgainstSchema(string json, string schemaJson, out string errorMessage)
{
try
{
JSchema schema = JSchema.Parse(schemaJson);
JObject jsonObject = JObject.Parse(json);

if (jsonObject.IsValid(schema))
{
errorMessage = null;
return true;
}
else
{
errorMessage = "JSON does not match the schema.";
return false;
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
return false;
}
}
}

Output

Valid JSON according to schema.

If the JSON does not conform to the schema, the error message will indicate why.


Conclusion

Using Newtonsoft.Json, you can easily validate the format of JSON data in your C# applications. While simple format validation ensures your JSON is syntactically correct, schema validation helps enforce data structures, making your application more robust. Combining both techniques ensures you handle JSON data confidently and efficiently.


Need Help with Your C# Projects?

We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.

CONTACT US NOW