【问题标题】:Ignore null and default value from serializer in web api忽略 web api 中序列化程序的 null 和默认值
【发布时间】:2016-08-01 14:12:59
【问题描述】:

我想从 Json 序列化中忽略那些为空的属性。 为此,我在 webapi.config 文件中添加了这一行。

config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};

public static void Register(HttpConfiguration config)
        {          
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{identifier}",
                defaults: new { identifier = RouteParameter.Optional }  
            );
            config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling= DefaultValueHandling.Ignore };
        }

但它并没有忽略那些为空的属性。

这是我的课

public class UserProfile
    {
        [JsonProperty("fullname")]
        public string FullName { get; set; }

        [JsonProperty("imageid")]
        public int ImageId { get; set; }

        [JsonProperty("dob")]
        public Nullable<DateTime> DOB { get; set; }
    }

是从web api返回的Json

    {
  "fullname": "Amit Kumar",
  "imageid": 0,
  "dob": null
}

我还没有赋值dob和imageid的值。

我关注了这个Link,但它并没有解决我的问题。

【问题讨论】:

  • 您想忽略序列化的任何对象中的每个 null 属性,还是需要选择性地决定要忽略哪个具有 null 值的属性?
  • @FedericoDipuma:我想在每个对象中忽略它,这就是我全局添加它的原因。
  • @MostafizurRahman:不。这不是重复的问题。

标签: c# asp.net json asp.net-web-api


【解决方案1】:

通过查看Newtonsoft.Json source code,我相信装饰类属性的JsonPropertyAttribute 会覆盖JsonSerializerSettings 中指定的默认NullValueHandling

要么删除此类属性(如果您想使用全局定义的 NullValueHandling)或明确指定 NullValueHandling

public class UserProfile
{
    [JsonProperty("fullname")]
    public string FullName { get; set; }

    [JsonProperty("imageid")]
    public int ImageId { get; set; }

    [JsonProperty("dob", NullValueHandling = NullValueHandling.Ignore)]
    public Nullable<DateTime> DOB { get; set; }
}

【讨论】:

  • 我删除了那些JsonProperty,但问题还是一样。
  • 这真是一种奇怪的行为。我试图在一个新的 Web API 项目中重现该问题,但一切正常。根据目前的信息,我不知道可能出了什么问题。尝试将 Startup.cs 或 Global.asax.cs 文件的内容添加到问题中。
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2013-04-11
  • 2013-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多