21

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",
   "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 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 JSON 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?

2
  • I cant think of situation where you will need kind of validation provided by you. There are plenty of people with names (first and surname) longer than 70 even 100 chars. Commented Aug 16, 2015 at 18:41
  • 1
    I'd rather look up for some unique validation rules like: age is positive number, date contains day-month-year, user provided at least 2 skills in every category. Commented Aug 16, 2015 at 18:44

2 Answers 2

18

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 :-

try{
JsonParser parser = new JsonParser();
parser.parse(passed_json_string);
} 
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

Example:-

"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.

Sign up to request clarification or add additional context in comments.

7 Comments

Hi Amit thanks, does it validate net.sf.json object?
Json is just a data format, you define a schema for Json and then just validate the incoming json against that schema.
@N3WOS what do you mean by "validation"? Do you want to check if incoming json data is valid (correct in terms of its specification) or do you want to check user input (age over 18, etc.)??
mastah I want to check the user input. A kind of data validation.
@AmitBhati could you provide a little bit more about validation JSON using schemas?
|
5
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;    
/**
         * 
         * @param inputJosn
         * @return
         * @throws IOException 
         * @throws JsonParseException 
         * @throws JsonProcessingException
         */
        private static boolean isJsonValid(String inputJosn) throws JsonParseException, IOException  {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
            JsonFactory factory = mapper.getFactory();
            JsonParser parser = factory.createParser(inputJosn);
            JsonNode jsonObj = mapper.readTree(parser);
            System.out.println(jsonObj.toString());


            return true;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.