Search code examples
json.netjson-serializationflurl

How to use Newtonsoft JSON serializer for all Flurl 4.0 calls globally or per specific client


I need to use Newtonsoft JSON serializer for all calls made via Flurl 4.0 (or at least for all calls made by a specific Flurl client), but I cannot figure out how to set it up. From the answer to the FLURL 4.0 use Newtonsoft JSON Serializer on a single request question, I see how to do it for each call, but this seems a bit tedious, since I would need to use the same settings for all calls. What is the correct way to (a) set it globally (i.e. not tied to a specific client) and (b) set it for all requests made by a given client? To create a client I use the following helper method:

public static IFlurlClient Create
(
    string url,
    string? proxy = null
)
{
    IFlurlClient client = string.IsNullOrEmpty(proxy)
        ? new FlurlClient(url)
        : new FlurlClientBuilder(url)
            .ConfigureInnerHandler(h => {
                h.Proxy = new WebProxy(proxy);
                h.UseProxy = true; })
            .Build();

    return client;
}

What do I need to inject into this method to make it work with Newtonsoft JSON serializer?


Solution

  • First install the Newtonsoft serializer from NuGet.

    If you just need it to work with the client you created in your code:

    client.Settings.JsonSerializer = new NewtonsoftJsonSearializer();
    

    The readme on the NuGet page linked above also mentions a couple other ways to use it: