如何在java中验证JSON对象?

N3W*_*WOS 12 java validation json rules

我使用sf.json库来映射我的Web应用程序中的传入请求的表单数据.

让我们说传入的请求是http:// localhost:8080/app/addProfile,表单数据为:

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"
}
Run Code Online (Sandbox Code Playgroud)

服务器端 :

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
}
...
...
...
Run Code Online (Sandbox Code Playgroud)

这种方法的主要问题是如果结构中有微小的修改JSON,那么整个代码需要修改.

是否有任何API可以配置验证所需的规则?

Ami*_*ati 12

您可以使用Json验证器: - https://github.com/fge/json-schema-validator

或者您可以尝试使用Google Gson解析Json并捕获语法异常以验证它,如下所示: -

try{
JsonParser parser = new JsonParser();
parser.parse(passed_json_string);
} 
catch(JsonSyntaxException jse){
System.out.println("Not a valid Json String:"+jse.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

对于通用数据验证,请在Json模式中定义规则,然后仅针对此模式验证传入的Json.
在模式中,您可以定义它可以包含的值的类型,范围等.
对于模式生成,您可以使用在线工具,如: - http://jsonschema.net/#/

您可以参考这篇文章,快速了解json架构: - http://json-schema.org/example1.html

例:-

"price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
Run Code Online (Sandbox Code Playgroud)

上面的代码定义了Json模式中的价格,当Json对象根据此模式进行验证时,它将确保价格不应该为零,它应该大于零,它应该是一个数字.如果在价格中传递字符串或零或某些负值,则验证将失败.


vaq*_*han 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;
        }
Run Code Online (Sandbox Code Playgroud)