2

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?

6
  • 1
    I am assuming your API is not being hit and you suspect the JSON to be in the incorrect format? Commented Sep 24, 2015 at 18:55
  • NO my API gets hit, and the input is Deserialised, but i expect an error instead cus it shouldn't Deserialise NOT properly formated JSON like no brases at the end Commented Sep 24, 2015 at 18:57
  • It's interesting because I would expect that deserialzing {ID:["1234"] would throw an exception because it's malformed. Also, {ID:["1234"]} is not valid json either...What serialization library are you using? JSON.NET? Commented Sep 24, 2015 at 19:05
  • Thanks for pointing that out, just edited it. Commented Sep 24, 2015 at 19:08
  • 1
    Have you tried using ModelState.IsValid to check if that fails? Commented Sep 24, 2015 at 19:12

2 Answers 2

2

I simple check at the beginning of a controller's method:

if (!Model.IsValid(ModelName))
{
    //handle error
}
else
{
    //continue 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Clearly Model.IsValid and the Deserialiser don't match. I would expect the input not to be Deserialsed if its not properly formatted but I got my answer for now.
Yah, I think there is some behavior where the Model Object gets instantiated as "null" regardless if the JSON got deserialized properly or not.
1

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

  • Valid JSON, that is
  • In the format you expect

See

for details.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.