How to validate a JSON object in java? -
i use sf.json library map form data incoming request in web application in java.
lets incoming request http://localhost:8080/app/addprofile form data as:
formdata: { "name":"applicant name", "age":"26", "academics":{ "college":"80", "inter":"67", "matriculation":"89" }, "skill":{ "computer":"c,c++,java", "maths":"limit,permutation,statistics" }, "dateofbirth":"09-07-1988" }
server side :
string requestformdata=request.getparameter("formdata"); jsonobject formdata = jsonobject.fromobject(requestformdata); string name= formdata.getstring("name"); if(name.length>70){ //error message length validation } if(!name.matches("regex name"){ //error message name validation } ... ... ...
the main problem approach if there minor modification in json
structure, entire code needs modified.
is there api can configure rules required validation?
you can use json validator: - https://github.com/fge/json-schema-validator
or can try parse json using google gson , catch syntax exception validate below :-
try{ jsonparser parser = new jsonparser(); parser.parse(passed_json_string); } catch(jsonsyntaxexception jse){ system.out.println("not valid json string:"+jse.getmessage()); }
for generic data validation, define rules in json schema , validate incoming json against schema.
in schema can define type of values can contain, range etc.
schema generation, can use online tool :- http://jsonschema.net/#/
you can refer post, have quick understanding of json schema:- http://json-schema.org/example1.html
example:-
"price": { "type": "number", "minimum": 0, "exclusiveminimum": true }
above code defines price in json schema, when json object validated against schema, ensure price shouldn't zero, should more 0 , should number. if string or 0 or negative value passed in price, validation fail.
Comments
Post a Comment