Skip to content

Commit

Permalink
Merge pull request #948 from RicoSuter/master
Browse files Browse the repository at this point in the history
Release v9.13.30
  • Loading branch information
RicoSuter authored Apr 17, 2019
2 parents 896e8a2 + f9956be commit 3095a52
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 40 deletions.
50 changes: 50 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,5 +259,55 @@ public async Task When_enum_property_is_not_required_in_Swagger2_then_it_is_null
//// Assert
Assert.Contains("private MyClassStatus? _status;", code);
}

[Fact]
public async Task When_array_item_enum_is_not_referenced_then_type_name_hint_is_property_name()
{
/// Arrange
var json = @"
{
""properties"": {
""foo"": {
""$ref"": ""#/definitions/NewOrderModel""
}
},
""definitions"": {
""NewOrderModel"": {
""type"": ""object"",
""properties"": {
""id"": {
""format"": ""int32"",
""type"": ""integer""
},
""name"": {
""type"": ""string""
},
""status"": {
""uniqueItems"": false,
""type"": ""array"",
""items"": {
""enum"": [
""Finished"",
""InProgress""
],
""type"": ""string""
}
}
}
}
}
}";
/// Act
var schema = await JsonSchema4.FromJsonAsync(json);

var settings = new CSharpGeneratorSettings();
var generator = new CSharpGenerator(schema, settings);

var code = generator.GenerateFile("Foo");

/// Assert
Assert.DoesNotContain("public enum Anonymous", code);
Assert.Contains("public enum Status", code);
}
}
}
4 changes: 3 additions & 1 deletion src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,9 @@ private string ResolveArrayOrTuple(JsonSchema4 schema)
{
if (schema.Item != null)
{
return string.Format(Settings.ArrayType + "<{0}>", Resolve(schema.Item, schema.Item.IsNullable(Settings.SchemaType), null));
var itemTypeNameHint = (schema as JsonProperty)?.Name;
var itemType = Resolve(schema.Item, schema.Item.IsNullable(Settings.SchemaType), itemTypeNameHint);
return string.Format(Settings.ArrayType + "<{0}>", itemType);
}

if (schema.Items != null && schema.Items.Count > 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.29</Version>
<Version>9.13.30</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.29</Version>
<Version>9.13.30</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.29</Version>
<Version>9.13.30</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
17 changes: 17 additions & 0 deletions src/NJsonSchema.Tests/Generation/DictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class EnumKeyDictionaryTest
public Dictionary<PropertyName, string> Mapping { get; set; }

public IDictionary<PropertyName, string> Mapping2 { get; set; }

public IDictionary<PropertyName, int?> Mapping3 { get; set; }
}

[Fact]
Expand All @@ -32,6 +34,21 @@ public async Task When_dictionary_key_is_enum_then_csharp_has_enum_key()

Assert.True(schema.Properties["Mapping2"].IsDictionary);
Assert.True(schema.Properties["Mapping2"].DictionaryKey.ActualSchema.IsEnumeration);

Assert.False(schema.Properties["Mapping2"].DictionaryKey.IsNullable(SchemaType.JsonSchema));
Assert.False(schema.Properties["Mapping2"].AdditionalPropertiesSchema.IsNullable(SchemaType.JsonSchema));
}

[Fact]
public async Task When_value_type_is_nullable_then_json_schema_is_nullable()
{
//// Act
var schema = await JsonSchema4.FromTypeAsync<EnumKeyDictionaryTest>();
var data = schema.ToJson();

//// Assert
Assert.True(schema.Properties["Mapping3"].IsDictionary);
Assert.True(schema.Properties["Mapping3"].AdditionalPropertiesSchema.IsNullable(SchemaType.JsonSchema));
}
}
}
2 changes: 1 addition & 1 deletion src/NJsonSchema.Yaml/NJsonSchema.Yaml.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net45</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.29</Version>
<Version>9.13.30</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema/Annotations/ItemsCanBeNullAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace NJsonSchema.Annotations
{
/// <summary>Annotation to specify that array items are nullable.</summary>
/// <summary>Annotation to specify that array items or dictionary values are nullable.</summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.Field)]
public class ItemsCanBeNullAttribute : Attribute
{
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema/Annotations/JsonSchemaTypeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
namespace NJsonSchema.Annotations
{
/// <summary>Specifies the type to use for JSON Schema generation.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)]
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false)]
public class JsonSchemaTypeAttribute : Attribute
{
/// <summary>Initializes a new instance of the <see cref="JsonSchemaTypeAttribute"/> class.</summary>
Expand Down
47 changes: 18 additions & 29 deletions src/NJsonSchema/Generation/JsonSchemaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public virtual async Task GenerateAsync<TSchemaType>(Type type, IEnumerable<Attr
if (typeDescription.IsDictionary)
{
typeDescription.ApplyType(schema);
await GenerateDictionaryAsync(schema, type, schemaResolver).ConfigureAwait(false);
await GenerateDictionaryAsync(schema, type, parentAttributes, schemaResolver).ConfigureAwait(false);
}
else
{
Expand Down Expand Up @@ -455,8 +455,11 @@ private async Task GenerateArray<TSchemaType>(
var itemType = type.GetEnumerableItemType();
if (itemType != null)
{
var itemIsNullable = parentAttributes?.OfType<ItemsCanBeNullAttribute>().Any() == true ||
itemType.Name == "Nullable`1";

schema.Item = await GenerateWithReferenceAndNullabilityAsync<JsonSchema4>(
itemType, null, parentAttributes?.OfType<ItemsCanBeNullAttribute>().Any() == true, schemaResolver, async (s, r) =>
itemType, null, itemIsNullable, schemaResolver, async (s, r) =>
{
if (Settings.GenerateXmlObjects)
{
Expand Down Expand Up @@ -505,28 +508,16 @@ private async Task GenerateEnum<TSchemaType>(
}

/// <exception cref="InvalidOperationException">Could not find value type of dictionary type.</exception>
private async Task GenerateDictionaryAsync<TSchemaType>(TSchemaType schema, Type type, JsonSchemaResolver schemaResolver)
private async Task GenerateDictionaryAsync<TSchemaType>(TSchemaType schema, Type type, IEnumerable<Attribute> parentAttributes, JsonSchemaResolver schemaResolver)
where TSchemaType : JsonSchema4, new()
{
var genericTypeArguments = type.GetGenericTypeArguments();

var keyType = genericTypeArguments.Length == 2 ? genericTypeArguments[0] : typeof(string);
if (keyType.GetTypeInfo().IsEnum)
{
var keySchema = await GenerateAsync(keyType, schemaResolver).ConfigureAwait(false);

var valueTypeDescription = Settings.ReflectionService.GetDescription(keyType, null, Settings);
if (valueTypeDescription.RequiresSchemaReference(Settings.TypeMappers))
{
schema.DictionaryKey = new JsonSchema4
{
Reference = keySchema
};
}
else
{
schema.DictionaryKey = keySchema;
}
schema.DictionaryKey = await GenerateWithReferenceAsync<JsonSchema4>(
keyType, null, schemaResolver).ConfigureAwait(false);
}

var valueType = genericTypeArguments.Length == 2 ? genericTypeArguments[1] : typeof(object);
Expand All @@ -536,20 +527,18 @@ private async Task GenerateDictionaryAsync<TSchemaType>(TSchemaType schema, Type
}
else
{
var additionalPropertiesSchema = await GenerateAsync(valueType, schemaResolver).ConfigureAwait(false);
var valueIsNullable = parentAttributes?.OfType<ItemsCanBeNullAttribute>().Any() == true ||
valueType.Name == "Nullable`1";

var valueTypeDescription = Settings.ReflectionService.GetDescription(valueType, null, Settings);
if (valueTypeDescription.RequiresSchemaReference(Settings.TypeMappers))
{
schema.AdditionalPropertiesSchema = new JsonSchema4
schema.AdditionalPropertiesSchema = await GenerateWithReferenceAndNullabilityAsync<JsonSchema4>(
valueType, null, valueIsNullable, schemaResolver/*, async (s, r) =>
{
Reference = additionalPropertiesSchema
};
}
else
{
schema.AdditionalPropertiesSchema = additionalPropertiesSchema;
}
// TODO: Generate xml for key
if (Settings.GenerateXmlObjects)
{
s.GenerateXmlObjectForItemType(keyType);
}
}*/).ConfigureAwait(false);
}

schema.AllowAdditionalProperties = true;
Expand Down
23 changes: 20 additions & 3 deletions src/NJsonSchema/JsonSchema4.Reference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ public virtual JsonSchema4 ActualTypeSchema
}
}

/// <summary>Gets a value indicating whether this is a schema reference ($ref, <see cref="HasAllOfSchemaReference"/> or <see cref="HasOneOfSchemaReference"/>).</summary>
/// <summary>Gets a value indicating whether this is a schema reference ($ref, <see cref="HasAllOfSchemaReference"/>, <see cref="HasOneOfSchemaReference"/> or <see cref="HasAnyOfSchemaReference"/>).</summary>
[JsonIgnore]
public bool HasReference => Reference != null || HasAllOfSchemaReference || HasOneOfSchemaReference;
public bool HasReference => Reference != null || HasAllOfSchemaReference || HasOneOfSchemaReference || HasAnyOfSchemaReference;

/// <summary>Gets a value indicating whether this is an allOf schema reference.</summary>
[JsonIgnore]
Expand Down Expand Up @@ -74,6 +74,20 @@ public virtual JsonSchema4 ActualTypeSchema
MultipleOf == null &&
IsEnumeration == false;

/// <summary>Gets a value indicating whether this is an anyOf schema reference.</summary>
[JsonIgnore]
public bool HasAnyOfSchemaReference => AnyOf.Count == 1 &&
AnyOf.Any(s => s.HasReference) &&
Type == JsonObjectType.None &&
AllOf.Count == 0 &&
OneOf.Count == 0 &&
Properties.Count == 0 &&
PatternProperties.Count == 0 &&
AllowAdditionalProperties &&
AdditionalPropertiesSchema == null &&
MultipleOf == null &&
IsEnumeration == false;

/// <summary>Gets or sets the type reference.</summary>
[JsonIgnore]
[Obsolete("Use the Reference property instead.")]
Expand All @@ -83,7 +97,7 @@ public JsonSchema4 SchemaReference
set => Reference = value;
}

/// <summary>Gets a value indicating whether this is a schema reference ($ref, <see cref="HasAllOfSchemaReference"/> or <see cref="HasOneOfSchemaReference"/>).</summary>
/// <summary>Gets a value indicating whether this is a schema reference ($ref, <see cref="HasAllOfSchemaReference"/>, <see cref="HasOneOfSchemaReference"/> or <see cref="HasAnyOfSchemaReference"/>).</summary>
[JsonIgnore]
[Obsolete("Use the HasReference property instead.")]
public bool HasSchemaReference => HasReference;
Expand All @@ -108,6 +122,9 @@ private JsonSchema4 GetActualSchema(IList<JsonSchema4> checkedSchemas)
if (HasOneOfSchemaReference)
return OneOf.First().GetActualSchema(checkedSchemas);

if (HasAnyOfSchemaReference)
return AnyOf.First().GetActualSchema(checkedSchemas);

return Reference.GetActualSchema(checkedSchemas);
}

Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema/NJsonSchema.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.0;netstandard2.0;net40;net45</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.29</Version>
<Version>9.13.30</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down

0 comments on commit 3095a52

Please sign in to comment.