RestSharp's built-in JSON serializer serializes all of an object's properties, even if they're null or otherwise the default value. How can I make it skip these properties?
An alternative, you can use other json libraries (json.net, servicestack.text, etc.) which support ignoring null values to serialize it first:
RestRequest request = new RestRequest();
...
string jsonString = ThirdPartySerialization(jsonObject);
request.AddParameter("application/json", jsonString, ParameterType.RequestBody);
You can use a custom IJsonSerializerStrategy
together with the default SimpleJson
JSON serializer to ignore null values.
The easiest way to do it is to extend the PocoJsonSerializerStrategy
like below.
public class IgnoreNullValuesJsonSerializerStrategy : PocoJsonSerializerStrategy
{
protected override bool TrySerializeUnknownTypes(object input, out object output)
{
bool returnValue = base.TrySerializeUnknownTypes(input, out output);
if (output is IDictionary<string, object> obj)
{
output = obj.Where(o => o.Value != null).ToDictionary(o => o.Key, o => o.Value);
}
return returnValue;
}
}
And then use it as the default serializer strategy.
SimpleJson.CurrentJsonSerializerStrategy = new IgnoreNullValuesJsonSerializerStrategy();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With