2016-04-11 30 views
5

我想忽略Json序列化中那些为null的属性。 为此,我在我的webapi.config文件中添加了此行。在web api中忽略来自序列化器的空值和默认值

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; } 
    } 

类是从网页API

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

我还没有分配DOB和图像标识的值的Json回报。

我按照这个Link,但它没有解决我的问题。

+0

你想忽略你序列化或你需要有选择地确定任何对象EVERY空属性哪些属性与空值忽略? –

+0

@FedericoDipuma:我想在每个对象中忽略它,这就是为什么我在全局添加它的原因。 –

+0

@MostafizurRahman:不,这不是一个重复的问题。 –

回答

0

通过查看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; } 
} 
+0

我删除了那些JsonProperty,但问题仍然是一样的。 –

+0

这确实是一个奇怪的行为。我试图在一个新的Web API项目中重现这个问题,但一切工作正常。根据目前的信息,我不知道什么是错的。尝试将Startup.cs或Global.asax.cs文件的内容添加到问题中。 –

+0

将它添加到gloabal.asax文件后工作。 –