如何在MVC4中强制WebAPI在json结果中将空字符串呈现为空

And*_*rus 4 c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

如何在json结果中的ASP.NET MVC4 Web API v.1中将空字符串属性呈现为空字符串?WebAPI将它们呈现为

"myproperty": null
Run Code Online (Sandbox Code Playgroud)

如何渲染这个

"myproperty": ""
Run Code Online (Sandbox Code Playgroud)

控制器是

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() });
        }
     }
Run Code Online (Sandbox Code Playgroud)

object是嵌套的,包含很多字符串属性.在构造函数中将它们全部设置为空字符串似乎很难看.API调用者需要空字符串或0表示小数,它不喜欢任何值中的null常量.

Bar*_*xto 8

你可以像这样装饰你的房产:

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string myproperty{ get; set; }
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将默认值处理设置为在全局配置中填充,如下所示:

GlobalConfiguration
.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;
Run Code Online (Sandbox Code Playgroud)

所以,你不需要将它装饰到每个属性.你只需要使用DefaultValue.