Smith5727
Smith5727

Reputation: 785

Blazor NSwag Newtonsoft.Json to System.Text.Json

I am using the following code to generate a C# Client API for my Blazor WebAssembly project.

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();
    }
}

Now I want to migrate from Newtonsoft.Json to System.Text.Json because I am experiencing very slow deserializations (up to several seconds) in some of my larger API requests.

I have found some migrations guides online but I want to continue using my NSwag toolchain as above to generate my API Client since it is working really well otherwise. Does anyone know how to tell the NSwag toolchain to instead use System.Text.Json rather than Newtonsoft.Json?

Upvotes: 4

Views: 4791

Answers (1)

Filip Kalous
Filip Kalous

Reputation: 91

You can set the Json Library you want to use to generate your client by setting:

JsonLibrary = CSharpJsonLibrary.SystemTextJson

in CSharpGeneratorSettings initialization.

Sadly, the generated file still contain some mentions of Newtonsoft.Json. Maybe newer version will work fine.

Upvotes: 9

Related Questions