Search code examples
c#restsharpjsonserializer

How to have .AddJsonBody ignore nulls in object in C# utilizing RestSharp


I'm having issues with getting my JsonBody to parse without the null fields so I just perform updates on fields I want within the object. I know I can get around this by just passing the values I want as a new object but was trying to have it accept whichever values weren't set to null in the object only.

var request = new RestRequest($"/example", Method.Patch)
            .AddJsonBody(object);
        

var response = await restClient.ExecuteAsync(request);

Attempted to add the below when I was creating my RestClient but it didn't the s.UseSystemTextJson portion for me to be able to add the JsonSerializerOptions

var client = new RestClient(
    options, 
    configureSerialization: s => s.UseSystemTextJson(new JsonSerializerOptions {...})
);

Also, attempted to add [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] to the object


Solution

  • Try this :

    var jsonOptions = new JsonSerializerOptions
    {
      IgnoreNullValues = true
    };
    

    It will exclude null values from the JSON.

    Pass it to the Serialize()

    var json = JsonSerializer.Serialize(object, jsonOptions);
    

    Create request like :

    var request = new RestRequest($"/example", Method.Patch)
            .AddParameter("application/json", json, ParameterType.RequestBody);