簡體   English   中英

Java / Android - 針對String模式驗證字符串JSON

[英]Java/Android - Validate String JSON against String schema

我找不到針對給定JSON模式String驗證JSON字符串的最簡單方法(作為參考,這是在Java中,在Android應用程序中運行)。

理想情況下,我只想傳入一個JSON字符串和一個JSON模式字符串,並返回一個關於它是否通過驗證的布爾值。 通過搜索,我找到了以下2個有希望的庫來完成這個:

http://jsontools.berlios.de/

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

然而,第一個看起來相當過時,支持不力。 我將庫實現到我的項目中,即使使用他們的JavaDocs,我也無法告訴如何正確構建“Validator”對象進行驗證。

類似的故事與第二個,似乎是最新的良好的測試代碼。 但是,對於我想要做的事情,這很簡單,對於如何專門完成我想要的事情(甚至在查看ValidateServlet.java文件之后)似乎有點令人生畏和困惑。

好奇,如果有人有一個好的方法來完成這個(從它看起來),需要的簡單任務,或者如果我可能需要堅持上面的第二個選項? 提前致謝!

非常感謝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>

那么以下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

請享用!

這基本上就是你鏈接的Servlet所做的,所以它可能不是一個單行,但它仍然具有表現力。

servlet上指定的useV4useId用於指定Default to draft v4 for Default to draft v4Use id for addressing validations選項。

你可以在網上看到它: 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();
}

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM