How to visualize null string properties as empty strings in ASP.NET MVC4 Web API v.1 as a result of json? WebAPI displays them as
"myproperty": null
how to do it how
"myproperty": ""
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() }); } }
nested and contains many string properties. Setting them all to empty lines in the constructor seems ugly. The API call needs empty strings or 0 for decimal places, it does not like the zero constant in any value.
You can decorate your properties as follows:
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public string myproperty{ get; set; }
, :
GlobalConfiguration .Configuration .Formatters .JsonFormatter .SerializerSettings .DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;
, . DefaultValue.
DefaultValue
public class Customer { private string _myproperty = String.Empty; public string myproperty { get { return _myproperty; }; set { _myproperty = value ?? String.Empty; } } }
I give a little overhead, but I will solve the problem
DataTable dt = (new tst()).Gettable(); string s = string.Empty; s = Newtonsoft.Json.JsonConvert.SerializeObject(dt); s= s.Replace("null", "\"\""); Object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(s); return Ok(obj);
By default, the web api works like this ... you don't need to change