Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp: How to skip serializing null values to JSON?

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?

like image 905
Bryan Avatar asked Nov 15 '13 17:11

Bryan


2 Answers

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);
like image 152
leo1987 Avatar answered Sep 18 '22 16:09

leo1987


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();
like image 23
Conyc Avatar answered Sep 20 '22 16:09

Conyc