System.Text.Json isn't a full replacement for Json.NET. It's built for speed with minimal allocations in mind, not feature completeness. If you want validations you can
- Use Json.NET
- Validate the objects after serialisation with the Validator class
- Create a custom converter
TheGeneral showed how to do #3. A custom validator would have to handle all validations explicitly and return some meaningful exception though. Throwing an ArgumentNullException
is enough if there's only a single property to check. Validating multiple properties would require something more complex like a ValidationException to include the validation results.
K. Scott Allen's article Manual Validation with Data Annotations shows how to do #2.
One option is to use the Validator.ValidateObject to validate an object and get a ValidationException
with all the failing validations :
try
{
var validationCtx=new ValidationContexgt(myFoo);
Validator.ValidateObject(myFoo,validationCtx);
}
catch(ValidatinException ex)
{
//Do something with the results.
}
This is OK if invalid objects are rare, as throwing exceptions is expensive. Perhaps a better option is to use Validator.TryValidateObject :
var results = new List<ValidationResult>();
var validationCtx=new ValidationContexgt(myFoo);
if(Validator.TryValidateObject(myFoo,validationCtx,results))
{
//Use the object
}
else
{
//Do something with the failed results
}