NJsonSchema to C# Classes - Definition handling

147 Views Asked by At

I try to translate a bunch of JSON Schema files to C# classes. There are ~40 schema files and one "commons.schema" file with definitions, that are referenced from the other files. ex: pooling.schema.json

{
  "$id": "https://testtest/agent2pooling.schema.json",  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "pooling",
  "type": "object",
  "properties": {
    "targetComponentId": {
      "$ref": "commons.schema.json#/definitions/ComponentId",
      "description": "the name of the component where the information is going to"
    },

 (more Properties..)
}

The property references this definition from the commons.schema.json file:


{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://testtest/commons.schema.json",
  "$comment": "comments.....",
  "definitions": {
    "ComponentId": {
      "type": "string",
      "description": "Component names (used in pool2pool messages)",
      "pattern": "(Pool1|Pool2)"
    },
 (more definitions..)
}

To translate all the JSON schema files to classes I wrote a c# program and use the Newtonsoft.JSON NuGet. I parse the commons.schema.json with this code:

var jsonMyExtClassSchema = File.ReadAllText(commonSchemaPath);
    var task = JsonSchema.FromJsonAsync(jsonMyExtClassSchema);
    task.Wait();
    JsonSchema jsonMyExtClassSchemaFromFile = task.Result;
    writeSchemaToFile(jsonMyExtClassSchemaFromFile, System.IO.Path.GetFileNameWithoutExtension(commonSchemaPath), targetDirectory);

The result is an empty class.

After this i use the parsed JSONSchema "jsonMyExtClassSchemaFromFile" and pass it into the JsonReferenceResolver:

var jsonSchemaMyClass = File.ReadAllText(jsonSchemaFilePath); 

    var task2 = JsonSchema.FromJsonAsync(
        jsonSchemaMyClass, System.IO.Path.GetDirectoryName(jsonSchemaFilePath),
        schema4 =>
        {
            JsonSchemaResolver schemaResolver = new JsonSchemaResolver(
                schema4, new JsonSchemaGeneratorSettings());
            var resolver = new JsonReferenceResolver(schemaResolver);
            resolver.AddDocumentReference(commonsSchemaFilePath, jsonMyExtClassSchemaFromFile);
            return resolver;
        });
    task2.Wait();
    var schemaMyClassFromFile = task2.Result;

The class "schemaMyClassFromFile" contains all the properties from the JSON schema file but also all the referenced definitions from the commons.schema.json file. So, each class that I parse this way, has its own set of "definitions".

My expectation would be, that all the commons-definitions are in one class and then used from all the other classes.

How can I achieve that?

0

There are 0 best solutions below