Dale
Dale

Reputation: 1731

JSON Serialisation - removing empty keys

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;

Upvotes: 8

Views: 3541

Answers (1)

L.B
L.B

Reputation: 116168

Json.Net has a setting for this

var str = JsonConvert.SerializeObject(obj, 
    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });

Upvotes: 15

Related Questions