RicoSuter / NJsonSchema

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

Option for added non-nullable properties to the RequiredProperties #1188

Open InspiringCode opened 4 years ago

InspiringCode commented 4 years ago

Wouldn’t it make sense to make non-nullable properties required? When I have a C# propertiy that is non-null and deserialize it without a JSON property for it, I would construct a C# object that violates its nullability claims.

RicoSuter commented 4 years ago

Maybe there is an option for that. However just because it’s not nullable doesnt mean its required - newtonsoft just “deserializes” to the default value (eg 0).

InspiringCode commented 4 years ago

Ok, but that doesn't really work for nun-nollable reference types since the default value is null, which violates exactly the not-null claim of the object contract.

RicoSuter commented 4 years ago

Can you provide a sample (C# and spec + spec type [OAI2/3 or JSONSchema])?

InspiringCode commented 1 year ago

@RicoSuter Sorry for my late reply! Here is the example:

#nullable enable

public class Domain {
    public string Name { get; set; } = null!;

    public string NetbiosName { get; set; }

    public string? ForestRoot { get; set; }

    public int? Order { get; set; }

    public int NumberOfSubdomains { get; set; }
}

Expected specs:

"Domain": {
    "type": "object",
    "additionalProperties": false,
    "required": [
      "name",
      "netbiosName"
    ],
    "properties": {
      "name": {
        "type": "string",
      },
      "netbiosName": {
        "type": "string"
      },
      "forestRoot": {
        "type": "string",
        "nullable": "true"
      },
      "order": {
        "type": "integer",
        "format": "int32",
        "nullable": "true"
      },
      "numberOfSubdomains": {
        "type": "integer",
        "format": "int32"
      }
    }
}

The actual json generated by NJsonSchema does not include non-nullable reference properties in the required list:

"Domain": {
    "type": "object",
    "additionalProperties": false,
    "required": [ ],
    "properties": {
      // same as before
    }
}

Could you add an option for this?