I would like to validate incoming json object for correctness at the server side. Is there a standard / optimal way to do that? What is your approach of validation?
Asked
Active
Viewed 8,708 times
4
-
What server side language are you using? A lot will depend on that. – mattmc3 Feb 24 '11 at 04:14
2 Answers
5
My advice - deserialize the JSON and see if it breaks. For example, if you're using C# on the server side, you can use the newfangled DataContractJsonSerializer
, or do it the old way with the JavaScriptSerializer
which is arguably much simpler.
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, object>>(jsonString);
EDIT: And now that it's come out that you're using Java, of course my C# example is not going to work for you, but the concept is the same. Stackoverflow already has some answers here: Convert a JSON string to object in Java ME?
-
Thanks for the response. I know the way to convert json to java object. I would want to do quick generic validation on it ( to check whether its valid ) before converting it into java object. – Harsha Hulageri Feb 24 '11 at 04:29
-
@Harsha Validating the JSON text would mean parsing it to some extent. Therefor, for correct json text (which should outnumber invalid json by a large factor in any decent application) you will end up doing double parsing. Is that really worth it? – rahulmohan Feb 24 '11 at 05:40
-
Many times you may want the validation to occur before the request hits the backend. In that case some sort of schema validation is in order. – TechTrip May 11 '12 at 09:37
3
Decode it with a JSON library. If it successfully decodes using a library that follows the specifications then it's valid.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
1Yeah one of quickest way is to decode it into java object and see if it throws error while decoding. I want to do a generic validation on given json object without converting it into java object. I dont want to create java object just for validation. Any of your favorite json library / utility that would help me? – Harsha Hulageri Feb 24 '11 at 04:35