Search code examples
c#system.text.jsonrefit

System.Text.Json in Refit can't handle null response from API


Suppose I have a Refit interface:

public interface SomeApi
{
    [Get("/DoStuff")]
    Task<MyClass> DoStuff();
} 

I register this refit client in my dependency injection with System.Text.Json:

services.AddRefitClient<SomeApi>(new RefitSettings(
                                    new SystemTextJsonContentSerializer(
                                        new JsonSerializerOptions
                                            {
                                                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                                            })))
        .ConfigureHttpClient(ConfigureClient(config));

This code used to use Newtonsoft.Json, and has been refactored to use System.Text.Json. However,my /DoStuff endpoint can return null. With System.Text.Json, this will throw an exception in my Refit client. With Newtonsoft this works fine.

How do I get the above code to work if my api endpoints can return null?


Solution

  • Figured it out with the help of @dbc . Since System.Text.Json is very strict about with is valid json and what isn't, you have two options: make your API return a valid json (in this case, {} instead of null), or revert back to using Newtonsoft (which is less strict).