Skip to content

Commit

Permalink
Fix bug that C# property not nullable when specified via reference (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
markm77 committed Jun 12, 2024
1 parent c3380c1 commit 4c76ebd
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -245,5 +245,48 @@ public async Task When_generating_from_json_schema_string_property_with_date_or_
Assert.Contains("public string Required { get; set; } = default!;", code);
Assert.Contains("public string? Optional { get; set; } = default!;", code);
}

[Fact]
public async Task
When_generating_from_json_schema_string_property_with_reference_is_optional_and_GenerateNullableOptionalProperties_is_set_then_CSharp_property()
{
//// Arrange
var schemaJson = @"
{
""type"": ""object"",
""required"": [
""required""
],
""properties"": {
""required"": { ""$ref"": ""#/$defs/requiredString"" },
""optional"": { ""$ref"": ""#/$defs/optionalString"" }
},
""$defs"": {
""requiredString"": { ""type"": ""string"" },
""optionalString"": { ""type"": ""string"" }
}
}
";

var schema = await JsonSchema.FromJsonAsync(schemaJson);

//// Act
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
ClassStyle = CSharpClassStyle.Poco,
SchemaType = SchemaType.OpenApi3,
DateType = "string",
DateTimeType = "string",
TimeType = "string",
TimeSpanType = "string",
GenerateNullableReferenceTypes = true,
GenerateOptionalPropertiesAsNullable = true
});
var code = generator.GenerateFile("MyClass");

//// Assert
Assert.Contains("public string Required { get; set; } = default!;", code);
Assert.Contains("public string? Optional { get; set; } = default!;", code);
}
}
}
14 changes: 7 additions & 7 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,6 @@ public string Resolve(JsonSchema schema, bool isNullable, string? typeNameHint,
throw new ArgumentNullException(nameof(schema));
}

schema = GetResolvableSchema(schema);

if (schema == ExceptionSchema)
{
return "System.Exception";
}

// Primitive schemas (no new type)
if (Settings.GenerateOptionalPropertiesAsNullable &&
schema is JsonSchemaProperty property &&
Expand All @@ -75,6 +68,13 @@ schema is JsonSchemaProperty property &&
isNullable = true;
}

schema = GetResolvableSchema(schema);

if (schema == ExceptionSchema)
{
return "System.Exception";
}

var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable;

if (schema.ActualTypeSchema.IsAnyType &&
Expand Down

0 comments on commit 4c76ebd

Please sign in to comment.