java s:schema,Java中的JSONSchema解析和处理

There is a perfect .NET library Json.NET Schema. I use it in my C# application to parse schemas and make a Dictionary with pairs "name_of_simple_element" - "simple_element". Then I process each pair and for example try to find "string" type elements with pattern "[a-z]" or "string" elements with maximumLength > 300.

Now I should create application with same functions in Java. It is very simple in C#:

Jschema schema = JSchema.Parse(string json);

IDictionary dict = schema.Properties;

... etc.

But i cant find same way to do that in Java. I need to convert this

{

"$schema": "http://json-schema.org/draft-04/schema#",

"id": "http://iitrust.ru",

"type": "object",

"properties": {

"regions": {

"id": "...regions",

"type": "array",

"items": {

"id": "http://iitrust.ru/regions/0",

"type": "object",

"properties": {

"id": {

"id": "...id",

"type": "string",

"pattern": "^[0-9]+$",

"description": "Идентификатор региона"

},

"name": {

"id": "...name",

"type": "string",

"maxLength": 255,

"description": "Наименование региона"

},

"code": {

"id": "...code",

"type": "string",

"pattern": "^[0-9]{1,3}$",

"description": "Код региона"

}

},

"additionalProperties": false,

"required": ["id",

"name",

"code"]

}

}

},

"additionalProperties": false,

"required": ["regions"]

}

to pseudocode dictionary/map like this

["...id" : "id": { ... };

"...name" : "name": { ... };

"...code": "code": { ... }]

What is the best way to do that?

解决方案

Ok, problem is resolved by Jackson library. Code below is based on generally accepted rule that JSON Schema object is always has a "properties" element, "array" node is always has a "items" element, "id" is always unique. This is my customer's standart format. Instead of a C#'s Dictionary I have got a Java's HashMap.

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;

...

static Map elementsMap = new HashMap<>();

public static void Execute(File file) {

ObjectMapper mapper = new ObjectMapper();

JsonNode root = mapper.readTree(file);

JsonNode rootNode = root.path("properties");

FillTheElementMap(rootNode);

}

private static void FillTheElementMap(JsonNode rootNode) {

for (JsonNode cNode : rootNode){

if(cNode.path("type").toString().toLowerCase().contains("array")){

for(JsonNode ccNode : cNode.path("items")){

FillTheElementMap(ccNode);

}

}

else if(cNode.path("type").toString().toLowerCase().contains("object")){

FillTheElementMap(cNode.path("properties");

}

else{

elementsMap.put(cNode.path("id").asText(), cNode);

}

}

### 回答1: 使用 Java 语言编写程序来校验 JSON Schema 是非常容易的,可以使用许多库和框架来帮助您实现它。有许多第三方库和框架可以用于校验 JSON 格式,这些库和框架包括:Jackson,Gson,Genson,Apache Commons,Hibernate Validator,JsonSchemaJsonPath 和 FastJSON。 ### 回答2: 在Java,可以使用现有的库来编写代码,使用jsonSchema来校验数据。下面是使用Java编写的示例代码: 首先,需要导入相关的依赖库,例如使用Jackson库来处理JSON数据和使用json-schema-validator库来执行jsonSchema校验。可以通过Maven或Gradle等构建工具来管理依赖。 接下来,创建一个方法来执行校验操作。首先,需要定义jsonSchema的规则,可以使用JSON字符串或从外部文件加载。然后,需要将待校验的数据转换为JSON对象,可以使用Jackson库将字符串解析JSON对象。 然后,使用json-schema-validator库JsonSchemaFactory类来创建JsonSchema实例。使用JsonSchema的validate方法对JSON数据进行校验,该方法会返回校验结果。 最后,根据校验结果进行相应的处理,可以输出校验失败的原因或执行其他操作。 以下是一个简单的示例代码: ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; public class JsonValidator { public static void main(String[] args) { String schema = "{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } } }"; String data = "{ \"name\": \"John\" }"; boolean isValid = validateData(schema, data); if (isValid) { System.out.println("Data is valid."); } else { System.out.println("Data is invalid."); } } public static boolean validateData(String schemaString, String dataString) { ObjectMapper objectMapper = new ObjectMapper(); JsonNode schemaNode, dataNode; try { schemaNode = objectMapper.readTree(schemaString); dataNode = objectMapper.readTree(dataString); } catch (Exception e) { e.printStackTrace(); return false; } JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault(); try { JsonSchema schema = schemaFactory.getJsonSchema(schemaNode); ProcessingReport report = schema.validate(dataNode); return report.isSuccess(); } catch (ProcessingException e) { e.printStackTrace(); return false; } } } ``` 以上代码使用了Jackson库将schema和数据解析JSON节点,然后使用json-schema-validator库来创建JsonSchema对象,并使用validate方法进行校验。最后根据校验结果输出相应的信息。 当运行以上代码时,如果数据满足schema的定义,会输出"Data is valid.",否则输出"Data is invalid."。这个示例使用了简单的schema和数据进行校验,实际使用可以根据需要定义更复杂的schema,并使用更复杂的校验逻辑。 ### 回答3: 使用Java编写可以使用以下步骤来使用jsonSchema校验数据。 首先,你需要引入json-schema-validator库。你可以在Maven或Gradle添加以下依赖项: 对于Maven: ```xml <dependency> <groupId>org.everit.json</groupId> <artifactId>org.everit.json.schema</artifactId> <version>1.12.1</version> </dependency> ``` 对于Gradle: ```groovy implementation 'org.everit.json:org.everit.json.schema:1.12.1' ``` 接下来,你需要创建一个json schema的字符串或从文件读取json schema。假设你有以下的json schema字符串: ```json String schemaStr = "{\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": {\n" + " \"type\": \"string\"\n" + " },\n" + " \"age\": {\n" + " \"type\": \"integer\"\n" + " }\n" + " },\n" + " \"required\": [\"name\", \"age\"]\n" + "}"; ``` 然后你可以使用下面的代码来校验数据: ```java import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; class Main { public static void main(String[] args) { String dataStr = "{\"name\":\"John\", \"age\":30}"; try { JSONObject jsonSchema = new JSONObject(new JSONTokener(schemaStr)); JSONObject jsonData = new JSONObject(new JSONTokener(dataStr)); Schema schema = SchemaLoader.load(jsonSchema); schema.validate(jsonData); System.out.println("数据是有效的"); } catch (ValidationException e) { System.out.println("数据无效:" + e.getMessage()); } } } ``` 以上代码将创建一个Schema对象,并使用Schema.validate方法来验证数据。如果数据有效,将输出“数据是有效的”,否则将输出"数据无效"及详细错误信息。 这就是使用Java编写jsonSchema校验数据的基本步骤。你可以根据自己的需求修改json schema和数据,并在代码进行相应的处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值