14

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.

1
  • Actually I'm trying to leave out. Commented Apr 14, 2012 at 1:50

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.