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

时间:2013-01-24 21:51:48

标签: 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文件之后)似乎有点令人生畏和困惑。

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

3 个答案:

答案 0 :(得分: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

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

<dependency>
    <groupId>com.github.fge</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.0.1</version>
</dependency>

然后以下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);
}

}

上述代码的结果是:

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

享受!

答案 1 :(得分:10)

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

servlet上指定的

useV4useId用于指定Default to draft v4Use 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();
}

答案 2 :(得分:2)

@Alex的答案在Android上适用于我,但要求我使用Multi-dex并添加:

    packagingOptions {
        pickFirst 'META-INF/ASL-2.0.txt'
        pickFirst 'draftv4/schema'
        pickFirst 'draftv3/schema'
        pickFirst 'META-INF/LICENSE'
        pickFirst 'META-INF/LGPL-3.0.txt'
    }

到我的build.gradle