How to make WebAPI in MVC4 display empty strings as empty as a result of json

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": ""
Controller

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() });
        }
     }
An object

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.

+4
source share
4 answers

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.

+8
public class Customer {
   private string _myproperty = String.Empty;
   public string myproperty 
   { 
      get { return _myproperty; }; 
      set { _myproperty = value ?? String.Empty; } 
   }
}
+2

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);
0
source

By default, the web api works like this ... you don't need to change

-5
source

All Articles