Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -347,17 +347,30 @@ JsonSchema CompleteSchema(ref GenerationState state, JsonSchema schema)
{
if (schema.Ref is null)
{
// A schema is marked as nullable if either
// 1. We have a schema for a property where either the getter or setter are marked as nullable.
// 2. We have a schema for a reference type, unless we're explicitly treating null-oblivious types as non-nullable.
bool isNullableSchema = propertyInfo != null
? propertyInfo.IsGetNullable || propertyInfo.IsSetNullable
: typeInfo.CanBeNull && !parentPolymorphicTypeIsNonNullable && !state.ExporterOptions.TreatNullObliviousAsNonNullable;

if (isNullableSchema)
if (IsNullableSchema(state.ExporterOptions))
{
schema.MakeNullable();
}

bool IsNullableSchema(JsonSchemaExporterOptions options)
{
// A schema is marked as nullable if either:
// 1. We have a schema for a property where either the getter or setter are marked as nullable.
// 2. We have a schema for a Nullable<T> type.
// 3. We have a schema for a reference type, unless we're explicitly treating null-oblivious types as non-nullable.

if (propertyInfo is not null)
{
return propertyInfo.IsGetNullable || propertyInfo.IsSetNullable;
}

if (typeInfo.IsNullable)
{
return true;
}

return !typeInfo.Type.IsValueType && !parentPolymorphicTypeIsNonNullable && !options.TreatNullObliviousAsNonNullable;
}
}

if (state.ExporterOptions.TransformSchemaNode != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,18 @@ public static IEnumerable<ITestData> GetTestDataCore()
}
""");

yield return new TestData<int?>(
Value: 42,
AdditionalValues: [null],
ExpectedJsonSchema: """{"type":["integer","null"]}""",
Options: new() { TreatNullObliviousAsNonNullable = true });

yield return new TestData<DateTimeOffset?>(
Value: DateTimeOffset.MinValue,
AdditionalValues: [null],
ExpectedJsonSchema: """{"type":["string","null"],"format":"date-time"}""",
Options: new() { TreatNullObliviousAsNonNullable = true });

// User-defined POCOs
yield return new TestData<SimplePoco>(
Value: new() { String = "string", StringNullable = "string", Int = 42, Double = 3.14, Boolean = true },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public sealed partial class JsonSchemaExporterTests_SourceGen()
[JsonSerializable(typeof(ReadOnlyMemory<byte>))]
[JsonSerializable(typeof(DateTime))]
[JsonSerializable(typeof(DateTimeOffset))]
[JsonSerializable(typeof(DateTimeOffset?))]
[JsonSerializable(typeof(TimeSpan))]
#if NET
[JsonSerializable(typeof(DateOnly))]
Expand Down
Loading