Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 760
Dale Avatar asked Nov 20 '12 11:11

Dale


1 Answers

Json.Net has a setting for this

var str = JsonConvert.SerializeObject(obj, 
    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
like image 115
L.B Avatar answered Sep 19 '22 07:09

L.B