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?

asahun
  • 195
  • 3
  • 16
  • 1
    I am assuming your API is not being hit and you suspect the JSON to be in the incorrect format? – PeonProgrammer Sep 24 '15 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 – asahun Sep 24 '15 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? – PeonProgrammer Sep 24 '15 at 19:05
  • Thanks for pointing that out, just edited it. – asahun Sep 24 '15 at 19:08
  • 1
    Have you tried using ModelState.IsValid to check if that fails? – PeonProgrammer Sep 24 '15 at 19:12
  • It seems like ModelState.IsValid is returning false even if its deserializsed. Thanks, I will take a look more. – asahun Sep 24 '15 at 19:20

2 Answers2

2

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

if (!Model.IsValid(ModelName))
{
    //handle error
}
else
{
    //continue 
}
PeonProgrammer
  • 1,445
  • 2
  • 15
  • 27
  • 1
    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. – asahun Sep 24 '15 at 19:29
  • Yah, I think there is some behavior where the Model Object gets instantiated as "null" regardless if the JSON got deserialized properly or not. – PeonProgrammer Sep 24 '15 at 19:36
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.

Community
  • 1
  • 1
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135