Removing Null Properties from Json in MVC Web Api

2019-04-04 10:20发布

I'm serializing objects and returning as json from my web service. However, I'm trying to omit null properties from serialized json. Is there a way to do this? I'm using Web Api MVC 4 beta.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-04 11:08

The ASP.NET Web API currently (there are plans to change it for the final release to use Json.Net) uses DataContractJsonSerializer by default to serialize JSON.

So you can control the serialization process with the standard DataContract/DataMember attributes. To skip null properties you can set the EmitDefaultValue to false.

[DataContract]
public class MyObjet
{
    [DataMember(EmitDefaultValue = false)]
    public string Prop1 { get; set; }

    [DataMember(EmitDefaultValue = false)]
    public string Prop2 { get; set; }
}

If you want to have more control on how the JSON responses are serialized you can use the WebAPIContrib package which contains formatters using Json.Net or the built in JavaScriptSeralizer.

查看更多
萌系小妹纸
3楼-- · 2019-04-04 11:11

In Json.Net you can use JsonPropertyAttribute with NullValueHandling=NullValueHandling.Ignore. Looks like here is no way to do this for whole class, only explicity for each class field/property.

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string SometimesNull { get; set; }

FYI. There is a reasons why Json.Net by default serialize properties with null values. Take a look, may be some of this reasons applicable to your cases.

查看更多
登录 后发表回答