nSwag Client: Is there a better/easier approach to affect PropertyNameCaseInsensitive?

969 Views Asked by At

We are attempting to integrate System.Text.Json into our REST API and rest clients, previously using Newtonsoft.

We are using nswag CSharpClientGenerator.GenerateFile to generate our REST API clients via code (not nSwag Studio).

Because of the casing differences between the property names and the json name, items are not correctly deserializing. We have been able to over come this by setting PropertyNameCaseInsensitive = true.

We were able to do this via a partial class as below:

    partial class MakeClient
    {
        partial void UpdateJsonSerializerSettings(JsonSerializerOptions settings)
        {
            settings.PropertyNameCaseInsensitive = true;
        }
    }

I really don't want to create these partial classes for every client.

Is there an easier way to do this, such as injecting JsonSerializerOptions into the client, or some type of global setting?

2

There are 2 best solutions below

1
On

Try setting the Newtonsoft's one of predefined resolvers: CamelCasePropertyNamesContractResolver in nSwag Setting like: Setting up Custom Resolver in Nswag Setting

Alternatively, if you are maintaining a separate nswag setting for each of your API Specification, you can add there too.

This resolver will be set up in your respective FromJson and ToJson methods in your schemas, provided you have enabled these methods to be generated via NSwag. There is a setting for that as well.

Setting to enable From and To Json methods

This will code generate as: Resolver set up in From and To Json Methods

0
On

To use System.Text.Json for NSwag generated API clients (with NSwag version later than v14 preview) and the base class:

  • remove Microsoft.AspNetCore.Mvc.NewtonsoftJson and other Newtonsoft related NuGet packages from you project references if any - just in case you don't yet. They're not needed.
  • use SystemTextJson and base class - add this to your nswag.json - e.g. BaseClient

enter image description here

  • add BaseClient.cs like this

enter image description here

  • so your generated clients will be calling UpdateJsonSerializerSettings method from the base class

![image](https://github.com/RicoSuter/NSwag/assets/1560778/67113fa8-2ced-44d1-a709-c98b33da92bf)