有一个完善的.NET库Json.NET Schema。我在我的 C# 应用程序中使用它来解析模式并生成 Dictionary<string, JSchema>
与对“name_of_simple_element” - “simple_element”。然后我处理每一对,例如尝试查找具有模式“[a-z]”的“字符串”类型元素或具有 maximumLength > 300 的“字符串”元素。
现在我应该在 Java 中创建具有相同功能的应用程序。在 C# 中非常简单:
Jschema schema = JSchema.Parse(string json);
IDictionary<string, JSchema> dict = schema.Properties;
... etc.
但我无法在 Java 中找到同样的方法来做到这一点。我需要转换这个
{
"$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"]
}
像这样伪代码字典/ map
["...id" : "id": { ... };
"...name" : "name": { ... };
"...code": "code": { ... }]
最好的方法是什么?
最佳答案
好的,问题已通过 Jackson library 解决.下面的代码基于普遍接受的规则,即 JSON Schema 对象始终具有“properties”元素,“array”节点始终具有“items”元素,“id”始终是唯一的。这是我客户的标准格式。而不是 C# 的 Dictionary<string, Jschema>
我有一个 Java 的 HashMap<String, JsonNode>
.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
...
static Map<String, JsonNode> 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);
}
}
关于java - Java中JSONSchema的解析与处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36078748/