We are working on a .Net core based web api application and for this we have a requirement to validate incoming request body which is JSON
format against the c# based type.
We are at this point evaluating NJsonSchema
library to see if it throws duplicate property error.
But looks like it doesnt support this validation. We also checked JSON
schema validator from NewtonSoft
but seems like it doesnt support duplicate property validations either.
Below is the minimized code using NJsonSchema
that we use -
using NewtonSoft.Json;
public class MyRequest
{
[JsonRequired]
[JsonProperty("name")]
public string Name { get; set; }
}
and when we pass a JSON object like this -
{"name":"abc","name":"xyz"}
We need our JSON validator to throw error for duplicate property
Our example test looks like this -
[Test]
public async System.Threading.Tasks.Task SchemaValidation_WithDuplicateProperty_Async()
{
var jsonString = await File.ReadAllTextAsync("Data//JsonWithDuplicateProperty.json");
var schema = JsonSchema.FromType<MyRequest>();
var errors = schema.Validate(jsonString);
Assert.That(errors.Count(), Is.EqualTo(1));
}
So my question - Has anyone done this in the past? Or are there any libraries for .net core
that provides JSON
validation for duplicate properties and/or can this be done using NJsonSchema
or NewtonSoft
.