2013-01-24 61 views
16

我無法找到最簡單的方法來針對給定的JSON模式字符串驗證JSON字符串(僅供參考,這是在Java中,在Android應用程序中運行)。Java/Android - 根據字符串模式驗證字符串JSON

理想情況下,我想只傳入一個JSON字符串和一個JSON模式字符串,並且它返回一個布爾值來表示它是否通過驗證。通過搜索,我發現以下2個前途庫實現這一點:

http://jsontools.berlios.de/

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

然而,第一個與似乎支持差相當過時。我將該庫實現到了我的項目中,甚至使用它們的JavaDocs,我無法確定如何正確構建用於驗證的「Validator」對象。

與第二個類似的故事,它似乎與最新的測試代碼一致。然而,對於我想要做的事情來說,這很簡單,對於如何專門完成我想要的事情(即使在查看ValidateServlet.java文件後),似乎有點令人生畏和困惑。

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

+2

作者......沒有你在自述文件中看到有代碼示例的鏈接? ;) – fge

+0

你好,謝謝你的偉大的圖書館!是的,我確實看到了代碼示例,並且在我的帖子中實際上提到了嵌入式鏈接(ValidateServlet.java文件)。再次感謝這個圖書館!偉大的東西:) – svguerin3

+0

我不是在談論這個例子:我在談論'com.github.fge.jsonschema.examples'在javadoc;)順便說一句,1.6.0出來了。 – fge

回答

10

這實質上就是你鏈接到的Servlet所做的事情,所以它可能不是一個單行的,但它仍然是表達性的。

useV4useId在servlet中指定,用於指定驗證選項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(); 
} 
+0

輝煌,謝謝!我想我可能只是需要在正確的方向上使用這個庫的正確方法。真的很感激它! – svguerin3

+1

請注意,該實現檢測'$ schema'並且默認爲草稿版本v3。在大多數情況下,您只需使用'JsonSchemaFactory.defaultFactory()'。 – fge

13

感恩感謝您對道格拉斯Crockford的和弗朗西斯Galiegue編寫基於Java的JSON架構處理器!在線測試儀http://json-schema-validator.herokuapp.com/index.jsp真棒!我真的很喜歡有用的錯誤消息(我只找到了一個失敗的例子),儘管行和列和/或上下文會更好(現在,您只能在JSON格式錯誤期間獲得行和列信息(Jackson提供) )。最後,我要感謝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

不錯的例子謝謝! – vatsa

+0

太棒了!謝謝 – neverwinter

2

@亞歷克斯的答案爲我工作在Android,但要求我多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' 
    } 

我的JSON-架構驗證這裏的build.gradle