【发布时间】: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