Suppress null properties from Orchard's web api response

Topics: Core, General, Troubleshooting
Dec 3, 2013 at 1:33 PM
Hi all,
I'm trying to remove null properties from my response without to fully succeed.

In standard .net web api it is sufficient to include the following in WebApiConfig.cs file:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

but I don't know how to do it in Orchard. The best solution that I found is to serialize the object inside the controller with

var str = JsonConvert.SerializeObject(results,
                new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
and then return the serialized string. The problem with this solution is that get double apices "" surrounding the json object in the response. This means that I don't have a json object but a string.

Any ideas?


Dec 7, 2013 at 10:11 AM
Double quotes are there because your JSON string is serialized to JSON again. If you want to perform serialization on your own and not rely on WebAPI for that there are a few options. The easiest is to manually create a HttpResponseMessage with your string as content by using Request.CreateResponse(...) and refactor your action to return this instead. There are lots of examples on the web.