我无法找到最简单的方法来验证一个JSON字符串对一个给定的JSON字符串的模式(以供参考,这是在Java中,Android应用程序运行)。
I am having trouble finding the most simple way to validate a JSON String against a given JSON-schema String (for reference, this is in Java, running in an Android app).
在理想情况下,我想只是传递一个JSON字符串和JSON-模式字符串,并返回一个布尔值,它是否通过了验证。通过搜索,我发现了以下2个有前途的库实现这一点:
Ideally, I'd like to just pass in a JSON String and a JSON-schema String, and it returns a boolean as to whether it passes the validation. Through searching, I have found the following 2 promising libraries for accomplishing this:
http://jsontools.berlios.de/
https://github.com/fge/json-schema-validator
不过,第一个似乎相当过时较差的支持。我实现了库到我的项目,甚至与他们的JavaDoc,我无法告诉如何正确建立一个验证器对象进行验证。
However, the first one seems fairly outdated with poor support. I implemented the library into my project, and even with their JavaDocs, I was unable to tell how to properly build a "Validator" object for validation.
相似的故事:第二个,这似乎是向上最新与良好的测试code。但是,对于我想做的事情,这是非常简单的,这似乎是一个有点令人生畏和混乱,如何具体实现我想要的(即使在看ValidateServlet.java文件)。
Similar story with the 2nd one, which seems to be up-to-date with good test code. However, for what I want to do, which is very simple, it seems to be a bit daunting and confusing as to how to specifically accomplish what I want (even after looking at the ValidateServlet.java file).
好奇,如果任何人有一个很好的方式任何其他建议来完成这个(从它看起来是),即需要的,或者如果我也许需要坚持从上面的第二选择简单的任务?在此先感谢!
Curious if anyone has any other suggestions on a good way to accomplish this (from what it seems), simple task that need, or if I perhaps need to stick with the 2nd option from above? Thanks in advance!
实际上这也正是这个Servlet您链接到呢,所以它可能不是一个班轮,但它仍然是前pressive。
This is essentially what the Servlet you linked to does, so it may not be a one-liner but it still is expressive.
useV4
和 USEID
作为servlet的指定,对指定的验证选项默认起草V4
和使用ID为解决
。
useV4
and useId
as specified on the servlet, are for specifying validations option for Default to draft v4
and Use id for addressing
.
您可以在网上看到:http://json-schema-validator.herokuapp.com/
public boolean validate(String jsonData, String jsonSchema, boolean useV4, boolean useId) throws Exception {
// create the Json nodes for schema and data
JsonNode schemaNode = JsonLoader.fromString(jsonSchema); // throws JsonProcessingException if error
JsonNode data = JsonLoader.fromString(jsonData); // same here
JsonSchemaFactory factory = JsonSchemaFactories.withOptions(useV4, useId);
// load the schema and validate
JsonSchema schema = factory.fromSchema(schemaNode);
ValidationReport report = schema.validate(data);
return report.isSuccess();
}