Reputation: 195
I want to validate the json input before it gets deserialised to my objects
Example:
{"ID": ["1234"]}
, is valid = and gets deserialised to my POCO class
{"ID": ["1234"
, is not a valid JSON and I want to throw an error
I want to throw an error but right now Web API gracefully handling it and deserialising to the appropriate class. Is there anyway I can intercept the conversion and validate the the Input json before it reaches my controller?
Upvotes: 2
Views: 5029
Reputation: 1535
I simple check at the beginning of a controller's method:
if (!Model.IsValid(ModelName))
{
//handle error
}
else
{
//continue
}
Upvotes: 2
Reputation: 74365
The only way to know whether or not your text is valid JSON or not is to try and parse it. If the parser throws an exception, it's not valid JSON. See How to make sure that string is Valid JSON using JSON.NET).
If you are using NewtonSoft's Json.Net, you can validate your JSON against a schema so you know you've got
See
for details.
Upvotes: 1