Skip to content

Commit

Permalink
Fix JsonSerializerParameterCode property for System.Text.Json (#3338)
Browse files Browse the repository at this point in the history
* Fix JsonSerializerParameterCode property for System.Text.Json

* Update NJS to v10.3.11

* Remove unnecessary brackets
  • Loading branch information
unchase authored Mar 7, 2021
1 parent c811f36 commit 8a963c9
Show file tree
Hide file tree
Showing 25 changed files with 150 additions and 74 deletions.
2 changes: 1 addition & 1 deletion src/NSwag.AspNet.Owin/NSwag.AspNet.Owin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Owin" Version="3.0.1" />
<PackageReference Include="Microsoft.Owin.StaticFiles" Version="3.0.1" />
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
<PackageReference Include="Owin" Version="1.0" />
</ItemGroup>
<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNet.WebApi/NSwag.AspNet.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.3" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.3" />
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NSwag.Annotations\NSwag.Annotations.csproj" />
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AssemblyLoader/NSwag.AssemblyLoader.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<DefineConstants>TRACE;RELEASE;FullNet;NET451</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
<PackageReference Include="System.Net.Http" Version="4.3.2" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.6' OR '$(TargetFramework)' == 'netstandard2.0' ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public string JsonSerializerParameterCode
{
parameterCode = _settings.CSharpGeneratorSettings.JsonLibrary == CSharpJsonLibrary.NewtonsoftJson ?
"new Newtonsoft.Json.JsonSerializerSettings { Converters = " + parameterCode.Substring(2) + " }" :
"// TODO(system.text.json): What to do here?";
parameterCode.Substring(2);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NJsonSchema.CodeGeneration.CSharp" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration.CSharp" Version="10.3.11" />
</ItemGroup>
</Project>
34 changes: 19 additions & 15 deletions src/NSwag.CodeGeneration.CSharp/Templates/Client.Class.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@
public {{ Class }}({{ ConfigurationClass }} configuration{% if InjectHttpClient %}, {{ HttpClientType }} httpClient{% endif %}) : base(configuration)
{
{% if InjectHttpClient -%}
_httpClient = httpClient;
_httpClient = httpClient;
{% endif -%}
{% elseif UseBaseUrl and HasBaseUrl == false -%}
public {{ Class }}(string baseUrl{% if InjectHttpClient -%}, {{ HttpClientType }} httpClient{% endif %})
{
BaseUrl = baseUrl;
BaseUrl = baseUrl;
{% if InjectHttpClient -%}
_httpClient = httpClient;
_httpClient = httpClient;
{% endif -%}
{% elseif InjectHttpClient -%}
public {{ Class }}({{ HttpClientType }} httpClient)
{
_httpClient = httpClient;
_httpClient = httpClient;
{% else -%}
public {{ Class }}()
{
Expand All @@ -50,13 +50,17 @@
var settings = {{ JsonSerializerParameterCode }};
{% if UseSystemTextJson == false and SerializeTypeInformation -%}
settings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
{% endif -%}
{% if UseSystemTextJson == true and JsonSerializerParameterCode contains "var converters = new System.Text.Json.Serialization.JsonConverter[]" -%}
foreach(var converter in converters)
settings.Converters.Add(converter);
{% endif -%}
UpdateJsonSerializerSettings(settings{% if UseRequestAndResponseSerializationSettings %}, isRequest{% endif %});
return settings;
}

{% if UseBaseUrl and GenerateBaseUrlProperty -%}
public string BaseUrl
public string BaseUrl
{
get { return _baseUrl; }
set { _baseUrl = value; }
Expand All @@ -83,7 +87,7 @@
{% endif -%}
{% endif -%}


{% if GeneratePrepareRequestAndProcessResponseAsAsyncMethods == false -%}
partial void PrepareRequest({{ HttpClientType }} client, System.Net.Http.HttpRequestMessage request, string url);
partial void PrepareRequest({{ HttpClientType }} client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
Expand Down Expand Up @@ -146,7 +150,7 @@
{% endfor -%}
{% for parameter in operation.QueryParameters -%}
{% if parameter.IsOptional -%}
if ({{ parameter.VariableName }} != null)
if ({{ parameter.VariableName }} != null)
{
{% template Client.Class.QueryParameter %}
}
Expand Down Expand Up @@ -277,7 +281,7 @@
{% else -%}
PrepareRequest(client_, request_, urlBuilder_);
{% endif -%}

var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

Expand Down Expand Up @@ -321,21 +325,21 @@
}
{% elseif operation.HasSuccessResponse -%}
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new {{ ExceptionClass }}("{{ operation.DefaultResponse.ExceptionDescription }}", status_, responseData_, headers_, null);
}
{% elseif operation.HasResultType -%}
{% if operation.WrapResponse and operation.UnwrappedResultType != "FileResponse" -%}
return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
{% else -%}
return {{ operation.UnwrappedResultDefaultValue }};
{% endif -%}
{% elseif operation.WrapResponse -%}
return new {{ ResponseClass }}(status_, headers_);
return new {{ ResponseClass }}(status_, headers_);
{% endif -%}
{% else -%}
{% if operation.HasSuccessResponse == false -%}
{% comment %}
{% comment %}
If the success response has already been explicitely declared, there is no need for this default code (because handled above).
Otherwise, return default values on success because we don't want to throw on "unknown status code".
Success is always expected
Expand All @@ -344,20 +348,20 @@
{
{% if operation.HasResultType -%}
{% if operation.WrapResponse and operation.UnwrappedResultType != "FileResponse" -%}
return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
{% else -%}
return {{ operation.UnwrappedResultDefaultValue }};
{% endif -%}
{% elseif operation.WrapResponse -%}
return new {{ ResponseClass }}(status_, headers_);
return new {{ ResponseClass }}(status_, headers_);
{% else -%}{% comment %} This method isn't expected to return a value. Just return. {% endcomment -%}
return;
{% endif -%}
}
else
{% endif -%}
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new {{ ExceptionClass }}("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
{% endif -%}
Expand Down
80 changes: 76 additions & 4 deletions src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public void When_generating_CSharp_code_then_output_contains_expected_classes()
{
// Arrange
var document = CreateDocument();
var json = document.ToJson();

//// Act
var settings = new CSharpClientGeneratorSettings { ClassName = "MyClass" };
Expand All @@ -34,6 +33,79 @@ public void When_generating_CSharp_code_then_output_contains_expected_classes()
Assert.Contains("class Address", code);
}

[Fact]
public void When_generating_CSharp_code_with_SystemTextJson_then_output_contains_expected_code()
{
// Arrange
var document = CreateDocument();

//// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();

// Assert
Assert.Contains("new System.Text.Json.JsonSerializerOptions()", code);
}

[Fact]
public void When_generating_CSharp_code_with_SystemTextJson_and_JsonSerializerSettingsTransformationMethod_then_output_contains_expected_code()
{
// Arrange
var document = CreateDocument();

//// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;
settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod = "TestJsonSerializerSettingsTransformationMethod";

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();

// Assert
Assert.Contains("TestJsonSerializerSettingsTransformationMethod(new System.Text.Json.JsonSerializerOptions())", code);
}

[Fact]
public void When_generating_CSharp_code_with_NewtonsoftJson_and_JsonSerializerSettingsTransformationMethod_then_output_contains_expected_code()
{
// Arrange
var document = CreateDocument();

//// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.NewtonsoftJson;
settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod = "TestJsonSerializerSettingsTransformationMethod";

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();

// Assert
Assert.Contains("TestJsonSerializerSettingsTransformationMethod(new Newtonsoft.Json.JsonSerializerSettings { })", code);
}

[Fact]
public void When_generating_CSharp_code_with_SystemTextJson_and_JsonConverters_then_output_contains_expected_code()
{
// Arrange
var document = CreateDocument();

//// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;
settings.CSharpGeneratorSettings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" };

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();

// Assert
Assert.Contains("new System.Text.Json.JsonSerializerOptions(); var converters = new System.Text.Json.Serialization.JsonConverter[] { new CustomConverter1(), new CustomConverter2() }", code);
Assert.Contains("foreach(var converter in converters)", code);
Assert.Contains("settings.Converters.Add(converter)", code);
}

[Fact]
public void When_generating_TypeScript_code_then_output_contains_expected_classes()
{
Expand All @@ -44,7 +116,7 @@ public void When_generating_TypeScript_code_then_output_contains_expected_classe
var generator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings
{
ClassName = "MyClass",
TypeScriptGeneratorSettings =
TypeScriptGeneratorSettings =
{
TypeStyle = TypeScriptTypeStyle.Interface
}
Expand Down Expand Up @@ -97,7 +169,7 @@ public async Task When_using_json_schema_with_references_in_service_then_referen
}

[Fact]
public void No_Brackets_in_Operation_Name()
public void No_Brackets_in_Operation_Name()
{
// Arrange
var path = "/my/path/with/{parameter_with_underscore}/and/{another_parameter}";
Expand All @@ -120,7 +192,7 @@ private static OpenApiDocument CreateDocument()
document.Paths["/Person"] = new OpenApiPathItem();
document.Paths["/Person"][OpenApiOperationMethod.Get] = new OpenApiOperation
{
Responses =
Responses =
{
{
"200", new OpenApiResponse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NJsonSchema.CodeGeneration.TypeScript" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration.TypeScript" Version="10.3.11" />
</ItemGroup>
</Project>
4 changes: 2 additions & 2 deletions src/NSwag.CodeGeneration/NSwag.CodeGeneration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
<PackageReference Include="NJsonSchema.CodeGeneration" Version="10.3.11" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="Microsoft.CSharp" />
Expand Down
14 changes: 7 additions & 7 deletions src/NSwag.Commands/NSwag.Commands.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
<Authors>Rico Suter</Authors>
<PackageIconUrl>https://raw.githubusercontent.com/RicoSuter/NSwag/master/assets/NuGetIcon.png</PackageIconUrl>
<Company />
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/RicoSuter/NSwag.git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/RicoSuter/NSwag.git</RepositoryUrl>
</PropertyGroup>
<PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
Expand Down Expand Up @@ -64,11 +64,11 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.PlatformAbstractions" Version="1.1.0" />
<PackageReference Include="NConsole" Version="3.9.6519.30868" />
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration.CSharp" Version="10.3.10" />
<PackageReference Include="NJsonSchema.CodeGeneration.TypeScript" Version="10.3.10" />
<PackageReference Include="NJsonSchema.Yaml" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
<PackageReference Include="NJsonSchema.CodeGeneration" Version="10.3.11" />
<PackageReference Include="NJsonSchema.CodeGeneration.CSharp" Version="10.3.11" />
<PackageReference Include="NJsonSchema.CodeGeneration.TypeScript" Version="10.3.11" />
<PackageReference Include="NJsonSchema.Yaml" Version="10.3.11" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net461'">
<Reference Include="Microsoft.CSharp" />
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core.Yaml/NSwag.Core.Yaml.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<RootNamespace>NSwag</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NJsonSchema.Yaml" Version="10.3.10" />
<PackageReference Include="NJsonSchema.Yaml" Version="10.3.11" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>
<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/NSwag.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net45'">
<Reference Include="Microsoft.CSharp" />
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Demo.Web/NSwag.Demo.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NJsonSchema, Version=10.3.10.0, Culture=neutral, PublicKeyToken=c2f9c3bdfae56102, processorArchitecture=MSIL">
<HintPath>..\packages\NJsonSchema.10.3.10\lib\net45\NJsonSchema.dll</HintPath>
<Reference Include="NJsonSchema, Version=10.3.11.0, Culture=neutral, PublicKeyToken=c2f9c3bdfae56102, processorArchitecture=MSIL">
<HintPath>..\packages\NJsonSchema.10.3.11\lib\net45\NJsonSchema.dll</HintPath>
</Reference>
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
<HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
Expand Down Expand Up @@ -291,7 +291,7 @@
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Demo.Web/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Namotion.Reflection" version="1.0.18" targetFramework="net46" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
<package id="NJsonSchema" version="10.3.10" targetFramework="net46" />
<package id="NJsonSchema" version="10.3.11" targetFramework="net46" />
<package id="Owin" version="1.0" targetFramework="net45" />
</packages>
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<DefineConstants>$(DefineConstants);TRACE;DEBUG</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NJsonSchema" Version="10.3.10" />
<PackageReference Include="NJsonSchema" Version="10.3.11" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'netcoreapp3.0' ">
<PackageReference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" Version="1.0.4" />
Expand Down
Loading

0 comments on commit 8a963c9

Please sign in to comment.