Blazor NSwag Newtonsoft.Json 到 System.Text.Json

Smi*_*727 4 c# asp.net-core nswag blazor system.text.json

我使用以下代码为我的 Blazor WebAssembly 项目生成 C# 客户端 API。

using (HttpResponseMessage response = client.GetAsync("https://localhost:5001/swagger/v1/swagger.json").Result)
{
    using (HttpContent contentapi = response.Content)
    {
        var json = contentapi.ReadAsStringAsync().Result;
        var document = await OpenApiDocument.FromJsonAsync(json);

        var settings = new CSharpClientGeneratorSettings
        {
            ClassName = "Client",
            CSharpGeneratorSettings =
            {
                Namespace = "MyProjectClient",
            }
        };

        var generator = new CSharpClientGenerator(document, settings);
        var code = generator.GenerateFile();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想从 Newtonsoft.Json 迁移到 System.Text.Json,因为我在一些较大的 API 请求中遇到非常慢的反序列化(长达几秒)。

我在网上找到了一些迁移指南,但我想继续使用上面的 NSwag 工具链来生成我的 API 客户端,因为否则它工作得非常好。有谁知道如何告诉 NSwag 工具链使用 System.Text.Json 而不是 Newtonsoft.Json?

小智 8

您可以通过以下设置来设置要用于生成客户端的 Json 库:

JsonLibrary = CSharpJsonLibrary.SystemTextJson
Run Code Online (Sandbox Code Playgroud)

CSharpGeneratorSettings初始化中。

遗憾的是,生成的文件仍然包含一些 Newtonsoft.Json 的提及。也许新版本可以正常工作。

  • 在“cmd”版本中,我使用:“/JsonLibrary:SystemTextJson” (4认同)