Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix output of JsonIgnore attributes #1522

Merged
merged 6 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
126 changes: 0 additions & 126 deletions src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -739,132 +739,6 @@ public async Task When_property_is_required_then_CSharp_code_is_correct()
AssertCompile(code);
}

[Fact]
public async Task When_using_SystemTextJson_JsonIgnoreAttributes_are_generated_based_on_optionality() {
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [""requiredValue"",""requiredRef""],
""properties"": {
""requiredValue"": { ""type"": ""integer"", ""format"": ""int32"" },
""requiredRef"": { ""type"": ""string"" },
""optionalValue"": { ""type"": ""integer"", ""format"": ""int32"" },
""optionalRef"": { ""type"": ""string"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
JsonLibrary = CSharpJsonLibrary.SystemTextJson
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.Contains(
Normalized(@"public int OptionalValue {"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""requiredValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""requiredRef"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalRef"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);
}

[Fact]
public async Task When_using_SystemTextJson_and_RequiredPropertiesMustBeDefined_is_false_JsonIgnoreAttributes_are_not_generated_for_required_properties() {
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [""required""],
""properties"": {
""required"": { ""type"": ""string"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
RequiredPropertiesMustBeDefined = false
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.DoesNotContain(
Normalized(@"
[System.Text.Json.Serialization.JsonIgnore
"),
Normalized(code)
);
}

[Fact]
public async Task When_using_SystemTextJson_and_RequiredPropertiesMustBeDefined_is_false_JsonIgnoreAttributes_are_still_generated_for_optional_properties() {
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [],
""properties"": {
""optional"": { ""type"": ""string"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
RequiredPropertiesMustBeDefined = false
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optional"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);
}

[Fact]
public void When_array_property_is_required_or_not_then_the_code_has_correct_initializer()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;

namespace NJsonSchema.CodeGeneration.CSharp.Tests
{
public class JsonIgnoreAttributesTests
{
[Fact]
public async Task When_using_SystemTextJson_JsonIgnoreAttributes_are_generated_based_on_optionality()
{
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [""requiredValue"",""requiredNullableValue"",""requiredRef""],
""properties"": {
""requiredValue"": { ""type"": ""integer"", ""format"": ""int32"" },
""requiredNullableValue"": { ""type"": [""integer"", ""null""], ""format"": ""int32"" },
""requiredRef"": { ""type"": ""string"" },
""optionalValue"": { ""type"": ""integer"", ""format"": ""int32"" },
""optionalNullableValue"": { ""type"": [""integer"", ""null""], ""format"": ""int32"" },
""optionalRef"": { ""type"": ""string"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
//GenerateNullableReferenceTypes = true,
//GenerateOptionalPropertiesAsNullable = true,
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.Contains(
Normalized(@"public int OptionalValue {"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""requiredValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""requiredNullableValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""requiredRef"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalNullableValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalRef"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);
}

[Fact]
public async Task When_using_SystemTextJson_and_RequiredPropertiesMustBeDefined_is_false_JsonIgnoreAttributes_are_not_generated_for_required_properties()
{
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [""required""],
""properties"": {
""required"": { ""type"": ""string"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
RequiredPropertiesMustBeDefined = false
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.DoesNotContain(
Normalized(@"
[System.Text.Json.Serialization.JsonIgnore
"),
Normalized(code)
);
}

[Fact]
public async Task When_using_SystemTextJson_and_RequiredPropertiesMustBeDefined_is_false_JsonIgnoreAttributes_are_still_generated_for_optional_properties()
{
//// Arrange
var schema = await JsonSchema.FromJsonAsync(@"{
""type"": ""object"",
""required"": [],
""properties"": {
""optionalRef"": { ""type"": ""string"" },
""optionalValue"": { ""type"": ""integer"", ""format"": ""int32"" },
""optionalNullableValue"": { ""type"": [""integer"", ""null""], ""format"": ""int32"" }
}
}");

var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
RequiredPropertiesMustBeDefined = false
});

static string Normalized(string str) =>
Regex.Replace(str, @"\s+", " ");

//// Act
var code = generator.GenerateFile("MyClass");

/// Assert
Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalRef"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
"),
Normalized(code)
);

Assert.Contains(
Normalized(@"
[System.Text.Json.Serialization.JsonPropertyName(""optionalNullableValue"")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
"),
Normalized(code)
);
}
}
}
38 changes: 31 additions & 7 deletions src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//-----------------------------------------------------------------------

using System.Globalization;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;

namespace NJsonSchema.CodeGeneration.CSharp.Models
Expand Down Expand Up @@ -64,17 +65,40 @@ public PropertyModel(
(_property.ActualTypeSchema.IsArray && _settings.GenerateImmutableArrayProperties) ||
(_property.ActualTypeSchema.IsDictionary && _settings.GenerateImmutableDictionaryProperties)
)) == false;

/// <summary>Indicates whether or not this property has a <see cref="JsonIgnoreCondition"/>.</summary>
public bool HasJsonIgnoreCondition => JsonIgnoreCondition != null;

/// <summary>Returns the System.Text.Json.Serialization.JsonIgnoreCondition value to be applied to the property.</summary>
public string JsonIgnoreCondition => _property switch {
{ IsRequired: false } => "System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull",
{ IsRequired: true } when _settings.RequiredPropertiesMustBeDefined => "System.Text.Json.Serialization.JsonIgnoreCondition.Never",
_ => null
};

public string JsonIgnoreCondition
{
get
{
var isValueType = IsValueType();
return _property switch
{
{ IsRequired: true } when _settings.RequiredPropertiesMustBeDefined => "System.Text.Json.Serialization.JsonIgnoreCondition.Never",
{ IsRequired: false } when isValueType && IsNullable => "System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull",
{ IsRequired: false } when isValueType && !IsNullable => "System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault",
{ IsRequired: false } when !isValueType => "System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull",
_ => null
};

bool IsValueType()
{
var valueTypeFormats = new string[] { "date", "date-time", "uuid" };
return _property.ActualTypeSchema.Type switch
{
JsonObjectType.Boolean => true,
JsonObjectType.Integer => true,
JsonObjectType.Number => true,
JsonObjectType.String => valueTypeFormats.Contains(_property.Format),
AroglDarthu marked this conversation as resolved.
Show resolved Hide resolved
_ => false,
};
}
}
}

/// <summary>Gets the json property required.</summary>
public string JsonPropertyRequiredCode
{
Expand Down