diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs index 7479567c3..bfebd7d06 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs @@ -61,6 +61,12 @@ public CSharpGeneratorSettings() /// (sets Required.Always when the property is required) (default: true). public bool RequiredPropertiesMustBeDefined { get; set; } + /// Gets or sets a value indicating whether a required property should be treated as nullable by + /// default (if the property is not explicitly market as nullable: false) + /// (sets Required.Default when the property is not required and not explicitly marked as nullable: false). + /// + public bool DefaultNonRequiredToNullable { get; set; } + /// Gets or sets a value indicating whether to generated data annotation attributes (default: true). public bool GenerateDataAnnotations { get; set; } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs index 62b3d8f35..98c7100b1 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs @@ -81,6 +81,17 @@ public string JsonPropertyRequiredCode { get { + if (_settings.DefaultNonRequiredToNullable && !_property.IsRequired) + { + if (_property.IsNullableRaw == false) + { + return "Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore"; + } + else + { + return "Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore"; + } + } if (_settings.RequiredPropertiesMustBeDefined && _property.IsRequired) { if (!_property.IsNullable(_settings.SchemaType))