RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.4k stars 535 forks source link

Recursive sample generation #1561

Closed leflings closed 1 year ago

leflings commented 2 years ago

Fixes #1560

This PR modifies SampleJsonDataGenerator to support re-use of definitions, and by extension, recursion.

See issue for the problem before.

Example 1

Now the following schema:

{
    "definitions": {
        "withNumber": {
            "type": "object",
            "required": ["value"],
            "properties": {
                "value": {
                    "type": "number"
                }
            }
        }
    },
    "type": "object",
    "required": ["number1", "number2"],
    "properties": {
        "number1": { "$ref": "#/definitions/withNumber" },
        "number2": { "$ref": "#/definitions/withNumber" }
    }
}

generates

{
  "number1": {
    "value": 0.0
  },
  "number2": {
    "value": 0.0
  }
}

Example 2

Schema:

{
    "definitions": {
        "data": {
            "type": "object",
            "required": ["body"],
            "properties": {
                "body": { "$ref": "#/definitions/data" }
            }
        }
    },
    "type": "object",
    "required": ["data"],
    "properties": {
        "data": { "$ref": "#/definitions/data" },
    }
}

generates:

{
  "data": {
    "body": {
      "body": {
        "body": null
      }
    }
  }
}

The level of recursion is controlled by a new setting on SampleJsonDataGeneratorSettings