Skip to content

Commit

Permalink
Add option to explicitly exclude types from schema
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Jan 22, 2024
1 parent 3585d60 commit 79a760f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using NJsonSchema.Annotations;
using NJsonSchema.Generation;
using Xunit;

namespace NJsonSchema.Tests.Generation.SystemTextJson
Expand All @@ -26,5 +28,58 @@ public async Task When_property_is_readonly_then_its_in_the_schema()
Assert.Contains(@"Name", data);
Assert.Contains(@"Description", data);
}

public class ContainerType1
{
public int Property { get; set; }
public NestedType1 NestedType { get; set; }
}

public class NestedType1
{
public int NestedProperty { get; set; }
}

[Fact]
public async Task When_type_is_excluded_then_it_should_not_be_in_the_schema()
{
//// Act
var schema = JsonSchema.FromType<ContainerType1>(new SystemTextJsonSchemaGeneratorSettings
{
ExcludedTypeNames = [typeof(NestedType1).FullName]
});
var data = schema.ToJson();

//// Assert
Assert.NotNull(data);
Assert.DoesNotContain(@"NestedType1", data);
Assert.Contains(@"Property", data);
}

public class ContainerType2
{
public int Property { get; set; }

[JsonSchemaIgnore]
public NestedType2 NestedType { get; set; }
}

public class NestedType2
{
public int NestedProperty { get; set; }
}

[Fact]
public async Task When_type_is_excluded_with_json_schema_ignore_attribute_then_it_should_not_be_in_the_schema()
{
//// Act
var schema = JsonSchema.FromType<ContainerType2>();
var data = schema.ToJson();

//// Assert
Assert.NotNull(data);
Assert.DoesNotContain(@"NestedType2", data);
Assert.Contains(@"Property", data);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ public override void GenerateProperties(JsonSchema schema, ContextualType contex
var ignored = propertyIgnored
|| schemaGenerator.IsPropertyIgnoredBySettings(accessorInfo)
|| accessorInfo.GetAttributes(true)
.FirstAssignableToTypeNameOrDefault("System.Text.Json.Serialization.JsonExtensionDataAttribute", TypeNameStyle.FullName) != null;
.FirstAssignableToTypeNameOrDefault("System.Text.Json.Serialization.JsonExtensionDataAttribute", TypeNameStyle.FullName) != null
|| settings.ExcludedTypeNames.Contains(accessorInfo.AccessorType.Type.FullName);

if (!ignored)
{
Expand Down

0 comments on commit 79a760f

Please sign in to comment.