From f85ca2440ca67e8a334ea340ff92519356aea82d Mon Sep 17 00:00:00 2001 From: mereth Date: Sun, 28 Apr 2024 16:42:04 +0200 Subject: [PATCH] fix STJ read only properties handling --- .../SystemTextJson/SystemTextJsonTests.cs | 34 +++++++++++++++++++ .../SystemTextJsonReflectionService.cs | 4 +-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/NJsonSchema.Tests/Generation/SystemTextJson/SystemTextJsonTests.cs b/src/NJsonSchema.Tests/Generation/SystemTextJson/SystemTextJsonTests.cs index 1b4a1998f..e5fec8915 100644 --- a/src/NJsonSchema.Tests/Generation/SystemTextJson/SystemTextJsonTests.cs +++ b/src/NJsonSchema.Tests/Generation/SystemTextJson/SystemTextJsonTests.cs @@ -12,6 +12,14 @@ public class HealthCheckResult public string Name { get; } public string Description { get; } + + private string PrivateReadOnlyProperty1 { get; } + + private string PrivateReadOnlyProperty2 => "TEST"; + + public static string PublicReadOnlyStaticProperty { get; } + + private static string PrivateReadOnlyStaticProperty { get; } } [Fact] @@ -26,5 +34,31 @@ public async Task When_property_is_readonly_then_its_in_the_schema() Assert.Contains(@"Name", data); Assert.Contains(@"Description", data); } + + [Fact] + public async Task When_property_is_private_and_readonly_then_its_not_in_the_schema() + { + //// Act + var schema = JsonSchema.FromType(); + var data = schema.ToJson(); + + //// Assert + Assert.NotNull(data); + Assert.False(data.Contains("PrivateReadOnlyProperty1"), data); + Assert.False(data.Contains("PrivateReadOnlyProperty2"), data); + } + + [Fact] + public async Task When_property_is_static_readonly_then_its_not_in_the_schema() + { + //// Act + var schema = JsonSchema.FromType(); + var data = schema.ToJson(); + + //// Assert + Assert.NotNull(data); + Assert.False(data.Contains("PublicReadOnlyStaticProperty"), data); + Assert.False(data.Contains("PrivateReadOnlyStaticProperty"), data); + } } } diff --git a/src/NJsonSchema/Generation/SystemTextJsonReflectionService.cs b/src/NJsonSchema/Generation/SystemTextJsonReflectionService.cs index 71cb2cea8..ae780e316 100644 --- a/src/NJsonSchema/Generation/SystemTextJsonReflectionService.cs +++ b/src/NJsonSchema/Generation/SystemTextJsonReflectionService.cs @@ -32,8 +32,8 @@ public override void GenerateProperties(JsonSchema schema, ContextualType contex } if (accessorInfo.MemberInfo is PropertyInfo propertyInfo && - (propertyInfo.GetMethod?.IsPrivate == true || propertyInfo.GetMethod?.IsStatic == true) && - (propertyInfo.SetMethod?.IsPrivate == true || propertyInfo.SetMethod?.IsStatic == true) && + (propertyInfo.GetMethod == null || propertyInfo.GetMethod.IsPrivate == true || propertyInfo.GetMethod.IsStatic == true) && + (propertyInfo.SetMethod == null || propertyInfo.SetMethod.IsPrivate == true || propertyInfo.SetMethod.IsStatic == true) && !propertyInfo.IsDefined(typeof(DataMemberAttribute))) { continue;