Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a custom JSON Serializer in Refit

Tags:

uwp

refit

Currently the API response includes two top level attributes which are of no use to my need.

a: {
   b: {
      c: [
           data: whichINeed
         ]
      }
   }

If I create models for this I would have unncessary root objects which I want to get rid of ? How can I do this in Refit for Windows App ?

like image 389
user5381191 Avatar asked Oct 14 '25 23:10

user5381191


2 Answers

You'll need NewtonsoftJsonContentSerializer that exists on package Refit.Newtonsoft.Json.

Then, add it to the RefitSettings:

RestService.For<T>("host"),
  new RefitSettings
  {
    ContentSerializer = new NewtonsoftJsonContentSerializer(jsonSerializerSettings)
  });
like image 170
Daniel Rusnok Avatar answered Oct 18 '25 00:10

Daniel Rusnok


If you are using Refit via dependency injection, you can configure it to use the standard .NET JSON settings to overwrite the Refit settings (You can obviously use different Serializers too):

 var jsonSerializerOptions = new System.Text.Json.JsonSerializerOptions();
 var refitSettings = new RefitSettings
    {
        ContentSerializer = new SystemTextJsonContentSerializer(jsonSerializerOptions)
    }; 
builder.Services
    .AddHttpClient()
    .AddRefitClient<IHierarchyScopeApi>(refitSettings)
    .ConfigureHttpClient(x =>
{
    x.BaseAddress = new Uri("https://localhost:7023/");
    x.DefaultRequestHeaders.Add("x-api-key", builder.Configuration["Authorization:ApiKey"]);
});
like image 39
Animalz Avatar answered Oct 18 '25 00:10

Animalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!