Java/Android - 针对String模式验证字符串JSON

svg*_*in3 16 java android json jsonschema

我找不到针对给定JSON模式String验证JSON字符串的最简单方法(作为参考,这是在Java中,在Android应用程序中运行).

理想情况下,我只想传入一个JSON字符串和一个JSON模式字符串,并返回一个关于它是否通过验证的布尔值.通过搜索,我找到了以下2个有希望的库来完成这个:

http://jsontools.berlios.de/

https://github.com/fge/json-schema-validator

然而,第一个看起来相当过时,支持不力.我将库实现到我的项目中,即使使用他们的JavaDocs,我也无法告诉如何正确构建"Validator"对象进行验证.

类似的故事与第二个,似乎是最新的良好的测试代码.但是,对于我想要做的事情,这很简单,对于如何专门完成我想要的事情(甚至在查看ValidateServlet.java文件之后)似乎有点令人生畏和困惑.

好奇,如果有人有一个好的方法来完成这个(从它看起来),需要的简单任务,或者如果我可能需要坚持上面的第二个选项?提前致谢!

小智 13

非常感谢Douglas Crockford和Francis Galiegue编写基于java的json架构处理器!而http://json-schema-validator.herokuapp.com/index.jsp上的在线测试人员真棒!我真的很喜欢有用的错误消息(我只找到了一个失败的例子),虽然行和列和/或上下文会更好(现在,你只能在JSON格式错误期间获得行和列信息(由杰克逊提供)最后,我要感谢Michael Droettboom的精彩教程(即使他只涉及Python,Ruby和C,同时显然忽略了所有的最佳语言:-)).

对于那些错过它的人(就像我最初做的那样),有一些例子可以在github.com/fge/json-schema-processor-examples找到.虽然这些示例非常令人印象深刻,但它们并不是最初请求的简单json验证示例(而且我也在寻找).简单的例子在github.com/fge/json-schema-validator/blob/master/src/main/java/com/github/fge/jsonschema/examples/Example1.java

亚历克斯上面的代码对我不起作用,但非常有帮助; 我的pom正在推出最新的稳定版本2.0.1版,并在我的maven pom.xml文件中插入了以下依赖项:

<dependency>
    <groupId>com.github.fge</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.0.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

那么以下java代码对我来说很好:

import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.report.ProcessingMessage;
import com.github.fge.jsonschema.report.ProcessingReport;
import com.github.fge.jsonschema.util.JsonLoader;


public class JsonValidationExample  
{

public boolean validate(String jsonData, String jsonSchema) {
    ProcessingReport report = null;
    boolean result = false;
    try {
        System.out.println("Applying schema: @<@<"+jsonSchema+">@>@ to data: #<#<"+jsonData+">#>#");
        JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
        JsonNode data = JsonLoader.fromString(jsonData);         
        JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); 
        JsonSchema schema = factory.getJsonSchema(schemaNode);
        report = schema.validate(data);
    } catch (JsonParseException jpex) {
        System.out.println("Error. Something went wrong trying to parse json data: #<#<"+jsonData+
                ">#># or json schema: @<@<"+jsonSchema+">@>@. Are the double quotes included? "+jpex.getMessage());
        //jpex.printStackTrace();
    } catch (ProcessingException pex) {  
        System.out.println("Error. Something went wrong trying to process json data: #<#<"+jsonData+
                ">#># with json schema: @<@<"+jsonSchema+">@>@ "+pex.getMessage());
        //pex.printStackTrace();
    } catch (IOException e) {
        System.out.println("Error. Something went wrong trying to read json data: #<#<"+jsonData+
                ">#># or json schema: @<@<"+jsonSchema+">@>@");
        //e.printStackTrace();
    }
    if (report != null) {
        Iterator<ProcessingMessage> iter = report.iterator();
        while (iter.hasNext()) {
            ProcessingMessage pm = iter.next();
            System.out.println("Processing Message: "+pm.getMessage());
        }
        result = report.isSuccess();
    }
    System.out.println(" Result=" +result);
    return result;
}

public static void main(String[] args)
{
    System.out.println( "Starting Json Validation." );
    JsonValidationExample app = new JsonValidationExample();
    String jsonData = "\"Redemption\"";
    String jsonSchema = "{ \"type\": \"string\", \"minLength\": 2, \"maxLength\": 11}";
    app.validate(jsonData, jsonSchema);
    jsonData = "Agony";  // Quotes not included
    app.validate(jsonData, jsonSchema);
    jsonData = "42";
    app.validate(jsonData, jsonSchema);
    jsonData = "\"A\"";
    app.validate(jsonData, jsonSchema);
    jsonData = "\"The pity of Bilbo may rule the fate of many.\"";
    app.validate(jsonData, jsonSchema);
}

}
Run Code Online (Sandbox Code Playgroud)

我上面代码的结果是:

Starting Json Validation.
Applying schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@ to data: #<#<"Redemption">#>#
 Result=true
Applying schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@ to data: #<#<Agony>#>#
Error. Something went wrong trying to parse json data: #<#<Agony>#># or json schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@. Are the double quotes included?
 Result=false
Applying schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@ to data: #<#<42>#>#
Processing Message: instance type does not match any allowed primitive type
 Result=false
Applying schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@ to data: #<#<"A">#>#
Processing Message: string is too short
 Result=false
Applying schema: @<@<{ "type": "string", "minLength": 2, "maxLength": 11}>@>@ to data: #<#<"The pity of Bilbo may rule the fate of many.">#>#
Processing Message: string is too long
 Result=false
Run Code Online (Sandbox Code Playgroud)

请享用!


Ale*_*lex 10

这基本上就是你链接的Servlet所做的,所以它可能不是一个单行,但它仍然具有表现力.

useV4并且useId在servlet上指定,用于为Default to draft v4和指定验证选项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();
}
Run Code Online (Sandbox Code Playgroud)