N3WOS N3WOS - 1 year ago 368
Java Question

How to validate a JSON object in java?

I use sf.json library to map form data for incoming request in my web application in java.

Lets say the incoming request is http://localhost:8080/app/addProfile with form data as:

formData: {
"name":"applicant Name",

Server Side :

String requestFormData=request.getParameter("formData");
JSONObject formData = JSONObject.fromObject(requestFormData);
String name= formData.getString("name");

//error message for length validation

if(!name.matches("regex for name"){
//error message for name validation

The main problem with this approach is if there is minor modification in the
structure, then the entire code needs to be modified.

Is there is any api where i can configure the rules which are required for validation?

Answer Source

You can use the Json validator: - https://github.com/fge/json-schema-validator

Or you can simply try to parse the Json using Google Gson and catch syntax exception to validate it like below :-

JsonParser parser = new JsonParser();
catch(JsonSyntaxException jse){
System.out.println("Not a valid Json String:"+jse.getMessage());

For generic data validation, define the rules in your Json schema and then just validate the incoming Json against this schema.
In schema you can define the type of values it can contain, range etc.
For schema generation, you can use online tool like :- http://jsonschema.net/#/

You can refer this post, to have quick understanding of json schema:- http://json-schema.org/example1.html


"price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true

Above code defines the price in Json schema, when Json object is validated against this schema, it will ensure that price shouldn't be zero, it should be more than zero and it should be a number. If a string or zero or some negative value is passed in price, the validation will fail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download