how to force WebAPI in MVC4 to render null strings as empty in json result

asp.net-mvc, asp.net-mvc-4, asp.net-web-api, c#, json

Solution

you can decorate your properties like this :

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string myproperty{ get; set; }

Note that you can set the default value handling to populate in a global config like this:

GlobalConfiguration
.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;

So, you don't need to decorate it to every property. You will only need to use the `DefaultValue`.

Problem

How to render null string properties as empty strings in ASP.NET MVC4 Web API v.1 in json result? WebAPI renders them as ``` "myproperty": null ``` how to render this as ``` "myproperty": "" ``` controller is ``` public class Customer { public string myproperty { get; set; } } public class CustomersController : ApiController { public HttpResponseMessage Get() { var cust = new Customer(); return Request.CreateResponse(HttpStatusCode.OK, new { customers = cust.ToArray() }); } } ``` object are nested and contain lot of string properties. Setting them all to empty strings in constructor seems ugly. API caller needs empty strings or 0 for decimals, it does not like null constant in any value.

Original source