I'm creating a HTTP service using the .Net Web API technology, I've created some DTO classes and when only a certain subset of data is needed I'm planning on only filling the DTOs with that data to minimise the amount of data transferred.
Is there any way of getting the JSON serialiser to ignore those data members that are empty? I realise there's the [JsonIgnore] and [ScriptIgnore] attributes which will ignore specific members, but I only want to ignore them if they are null or empty.
[Edit]
Thanks to L.B below
I added the following to WebApiConfig.cs to enable this in Web API:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
Json.Net has a setting for this
var str = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
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