Skip to content

Commit

Permalink
Merge pull request #977 from RicoSuter/master
Browse files Browse the repository at this point in the history
Release v10.0.2
  • Loading branch information
RicoSuter authored May 22, 2019
2 parents 83e125f + cb21e4a commit c357cb9
Show file tree
Hide file tree
Showing 55 changed files with 812 additions and 51 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ NJsonSchema for .NET

NJsonSchema is a .NET library to read, generate and validate JSON Schema draft v4+ schemas. The library can read a schema from a file or string and validate JSON data against it. A schema can also be generated from an existing .NET class. With the code generation APIs you can generate C# and TypeScript classes or interfaces from a schema.

The library uses [Json.NET](http://james.newtonking.com/json) to read and write JSON data.
The library uses [Json.NET](http://james.newtonking.com/json) to read and write JSON data and [Namotion.Reflection](https://github.com/RicoSuter/Namotion.Reflection) for additional .NET reflection APIs.

**NuGet packages:**
- [NJsonSchema](https://www.nuget.org/packages/NJsonSchema) (.NET Standard 1.0 & 2.0/.NET 4.5/.NET 4.0): JSON Schema parsing, validation and generation classes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1737,7 +1737,9 @@ private static void AssertCompile(string code)

var sb = new StringBuilder();
foreach (var e in errors)
{
sb.AppendLine($"{e.Id} at {e.Location}: {e.GetMessage()}");
}

Assert.Empty(sb.ToString());
}
Expand Down
6 changes: 6 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ protected override CodeArtifact GenerateType(JsonSchema schema, string typeNameH
var typeName = _resolver.GetOrGenerateTypeName(schema, typeNameHint);

if (schema.IsEnumeration)
{
return GenerateEnum(schema, typeName);
}
else
{
return GenerateClass(schema, typeName);
}
}

private CodeArtifact GenerateClass(JsonSchema schema, string typeName)
Expand All @@ -124,7 +128,9 @@ private void RenamePropertyWithSameNameAsClass(string typeName, IEnumerable<Prop
{
var number = 1;
while (properties.Any(p => p.PropertyName == typeName + number))
{
number++;
}

propertyWithSameNameAsClass.PropertyName = propertyWithSameNameAsClass.PropertyName + number;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,26 @@ public static string GenerateJsonSerializerParameterCode(CSharpGeneratorSettings
else
{
if (hasJsonConverters)
{
return ", " + GenerateConverters(jsonConverters);
}
else
{
return string.Empty;
}
}
}

private static string GenerateConverters(List<string> jsonConverters)
{
if (jsonConverters.Any())
{
return "new Newtonsoft.Json.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }";
}
else
{
return string.Empty;
}
}
}
}
42 changes: 42 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,23 @@ public override string Resolve(JsonSchema schema, bool isNullable, string typeNa
public string Resolve(JsonSchema schema, bool isNullable, string typeNameHint, bool checkForExistingSchema)
{
if (schema == null)
{
throw new ArgumentNullException(nameof(schema));
}

schema = GetResolvableSchema(schema);

if (schema == ExceptionSchema)
{
return "System.Exception";
}

// Primitive schemas (no new type)

if (schema.ActualTypeSchema.IsAnyType && !schema.HasReference)
{
return "object";
}

var type = schema.ActualTypeSchema.Type;
if (type == JsonObjectType.None && schema.ActualTypeSchema.IsEnumeration)
Expand All @@ -77,30 +83,46 @@ public string Resolve(JsonSchema schema, bool isNullable, string typeNameHint, b
}

if (type.HasFlag(JsonObjectType.Number))
{
return ResolveNumber(schema.ActualTypeSchema, isNullable);
}

if (type.HasFlag(JsonObjectType.Integer) && !schema.ActualTypeSchema.IsEnumeration)
{
return ResolveInteger(schema.ActualTypeSchema, isNullable, typeNameHint);
}

if (type.HasFlag(JsonObjectType.Boolean))
{
return ResolveBoolean(isNullable);
}

if (type.HasFlag(JsonObjectType.String) && !schema.ActualTypeSchema.IsEnumeration)
{
return ResolveString(schema.ActualTypeSchema, isNullable, typeNameHint);
}

if (schema.IsBinary)
{
return "byte[]";
}

// Type generating schemas

if (schema.Type.HasFlag(JsonObjectType.Array))
{
return ResolveArrayOrTuple(schema);
}

if (schema.IsDictionary)
{
return ResolveDictionary(schema);
}

if (schema.ActualTypeSchema.IsEnumeration)
{
return GetOrGenerateTypeName(schema, typeNameHint) + (isNullable ? "?" : string.Empty);
}

return GetOrGenerateTypeName(schema, typeNameHint);
}
Expand All @@ -123,27 +145,41 @@ protected override bool IsDefinitionTypeSchema(JsonSchema schema)
private string ResolveString(JsonSchema schema, bool isNullable, string typeNameHint)
{
if (schema.Format == JsonFormatStrings.Date)
{
return isNullable && Settings.DateType?.ToLowerInvariant() != "string" ? Settings.DateType + "?" : Settings.DateType;
}

if (schema.Format == JsonFormatStrings.DateTime)
{
return isNullable && Settings.DateTimeType?.ToLowerInvariant() != "string" ? Settings.DateTimeType + "?" : Settings.DateTimeType;
}

if (schema.Format == JsonFormatStrings.Time)
{
return isNullable && Settings.TimeType?.ToLowerInvariant() != "string" ? Settings.TimeType + "?" : Settings.TimeType;
}

if (schema.Format == JsonFormatStrings.TimeSpan)
{
return isNullable && Settings.TimeSpanType?.ToLowerInvariant() != "string" ? Settings.TimeSpanType + "?" : Settings.TimeSpanType;
}

if (schema.Format == JsonFormatStrings.Uri)
{
return "System.Uri";
}

#pragma warning disable 618 // used to resolve type from schemas generated with previous version of the library

if (schema.Format == JsonFormatStrings.Guid || schema.Format == JsonFormatStrings.Uuid)
{
return isNullable ? "System.Guid?" : "System.Guid";
}

if (schema.Format == JsonFormatStrings.Base64 || schema.Format == JsonFormatStrings.Byte)
{
return "byte[]";
}

#pragma warning restore 618

Expand All @@ -158,18 +194,24 @@ private static string ResolveBoolean(bool isNullable)
private string ResolveInteger(JsonSchema schema, bool isNullable, string typeNameHint)
{
if (schema.Format == JsonFormatStrings.Byte)
{
return isNullable ? "byte?" : "byte";
}

if (schema.Format == JsonFormatStrings.Long || schema.Format == "long")
{
return isNullable ? "long?" : "long";
}

return isNullable ? "int?" : "int";
}

private static string ResolveNumber(JsonSchema schema, bool isNullable)
{
if (schema.Format == JsonFormatStrings.Decimal)
{
return isNullable ? "decimal?" : "decimal";
}

return isNullable ? "double?" : "double";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings,
AllProperties = Properties.Concat(BaseClass.AllProperties).ToArray();
}
else
{
AllProperties = Properties;
}
}

/// <summary>Gets or sets the class name.</summary>
Expand Down
24 changes: 24 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,24 @@ public string JsonPropertyRequiredCode
if (_settings.RequiredPropertiesMustBeDefined && _property.IsRequired)
{
if (!_property.IsNullable(_settings.SchemaType))
{
return "Newtonsoft.Json.Required.Always";
}
else
{
return "Newtonsoft.Json.Required.AllowNull";
}
}
else
{
if (!_property.IsNullable(_settings.SchemaType))
{
return "Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
}
else
{
return "Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
}
}
}
}
Expand All @@ -90,7 +98,9 @@ public bool RenderRequiredAttribute
get
{
if (!_settings.GenerateDataAnnotations || !_property.IsRequired || _property.IsNullable(_settings.SchemaType))
{
return false;
}

return _property.ActualTypeSchema.IsAnyType ||
_property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Object) ||
Expand All @@ -105,10 +115,14 @@ public bool RenderRangeAttribute
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}

if (!_property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Number) && !_property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Integer))
{
return false;
}

return _property.Maximum.HasValue || _property.Minimum.HasValue;
}
Expand Down Expand Up @@ -164,10 +178,14 @@ public bool RenderStringLengthAttribute
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}

if (_property.IsRequired && _property.MinLength == 1 && _property.MaxLength == null)
{
return false; // handled by RequiredAttribute
}

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) &&
(_property.MinLength.HasValue || _property.MaxLength.HasValue);
Expand All @@ -186,7 +204,9 @@ public bool RenderMinLengthAttribute
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Array) && _property.MinItems > 0;
}
Expand All @@ -201,7 +221,9 @@ public bool RenderMaxLengthAttribute
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Array) && _property.MaxItems > 0;
}
Expand All @@ -216,7 +238,9 @@ public bool RenderRegularExpressionAttribute
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) &&
!string.IsNullOrEmpty(_property.Pattern);
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>10.0.1</Version>
<Version>10.0.3</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 @@ -104,25 +104,37 @@ private static bool IsDateTime(string format, TypeScriptDateTimeType type)
if (type == TypeScriptDateTimeType.Date)
{
if (format == JsonFormatStrings.DateTime)
{
return true;
}

if (format == JsonFormatStrings.Time)
{
return false;
}

if (format == JsonFormatStrings.TimeSpan)
{
return false;
}
}
else if (type == TypeScriptDateTimeType.MomentJS ||
type == TypeScriptDateTimeType.OffsetMomentJS)
{
if (format == JsonFormatStrings.DateTime)
{
return true;
}

if (format == JsonFormatStrings.Time)
{
return true;
}

if (format == JsonFormatStrings.TimeSpan)
{
return true;
}
}
return false;
}
Expand All @@ -134,21 +146,27 @@ private static bool IsDate(string format, TypeScriptDateTimeType type)
if (type == TypeScriptDateTimeType.Date)
{
if (format == JsonFormatStrings.Date)
{
return true;
}
}
else if (type == TypeScriptDateTimeType.MomentJS ||
type == TypeScriptDateTimeType.OffsetMomentJS)
{
if (format == JsonFormatStrings.Date)
{
return true;
}
}
return false;
}

private static bool IsNewableObject(JsonSchema schema, DataConversionParameters parameters)
{
if (schema.ActualTypeSchema.IsEnumeration)
{
return false;
}

return parameters.Resolver.GeneratesType(schema);
}
Expand Down
Loading

0 comments on commit c357cb9

Please sign in to comment.