2

There is a perfect .NET library Json.NET Schema. I use it in my C# application to parse schemas and make a Dictionary<string, JSchema> 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<string, JSchema> 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?

kirill.login
  • 899
  • 1
  • 13
  • 28
  • See [here](https://github.com/fge/json-schema-validator); however this library works very differently. – fge Mar 18 '16 at 07:53

3 Answers3

4

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<string, Jschema> I have got a Java's 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);
        }
    }
kirill.login
  • 899
  • 1
  • 13
  • 28
2

A good option for you should be this Java implementation of JSONPath.

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONObject;
...
DocumentContext context = JsonPath.parse(jsonSchemaFile);

//"string" elements with maximumLength == 255
List<Map<String, JSONObject>> arr2 = context.read(
    "$..[?(@.type == 'string' && @.maxLength == 255)]");

And if you want to create a JsonSchema from Java code, you could use jackson-module-jsonSchema.

If you want to validate a JsonSchema, then the library from fge is an option: json-schema-validator

Meiko Rachimow
  • 4,664
  • 2
  • 25
  • 43
  • Is it possible to use JsonPath without maven? I develop in protected local network without internet. – kirill.login Mar 18 '16 at 11:52
  • sorry, the link to jsonPath was false, i edited my answer. – Meiko Rachimow Mar 18 '16 at 14:01
  • to use it without maven is no problem. but you have to download the library and all of its dependencies. to download the dependencies i would use maven. create an empty maven project like described here: https://maven.apache.org/guides/getting-started/ . Put jsonpath as a depenendency into the pom.xml. And see http://stackoverflow.com/questions/7908090/downloading-all-maven-dependencies-to-a-directory-not-in-repository – Meiko Rachimow Mar 18 '16 at 14:07
  • as an alternative, you could fetch the sources from: https://github.com/jayway/JsonPath install gradle and build the sources. – Meiko Rachimow Mar 18 '16 at 14:09
1

You may want to take a look at this library, it's helped me with similar requirements. With a couple lines of code you can traverse a pretty straightforward Java object model that describes a JSON schema. https://github.com/jimblackler/jsonschemafriend (Apache 2.0 license)

From the README:

jsonschemafriend is a JSON Schema loader and validator, delivered as a Java library...
It is compatible with the following metaschemas

http://json-schema.org/draft-03/schema#
http://json-schema.org/draft-04/schema#
http://json-schema.org/draft-06/schema#
http://json-schema.org/draft-07/schema#
https://json-schema.org/draft/2019-09/schema
Oren
  • 1,796
  • 1
  • 15
  • 17