If you use a DataContractSerializer (or, in this case, a DataContractJsonSerializer ), you can use the DataMember(EmitDefaultValue = false)] decoration DataMember(EmitDefaultValue = false)] in your class. That way, you can set properties that you don't want to serialize by default (i.e. null for strings, 0 for int, etc.), and they won't.
If you use the ASP.NET web API, you should be aware that the default JSON serializer is not DataContractJsonSerializer (DCJS), but JSON.NET. Therefore, if you have not explicitly configured your JsonMediaTypeFormatter to use DCJS, you need another attribute to get the same behavior ( JsonProperty and its JsonProperty property).
In the code below, only two elements that were assigned in this Car object are serialized using both serializers. Please note that you can remove one of the attributes if you intend to use only one of them.
public class StackOverflow_12465285 { [DataContract] public class Car { private int savedId; private string savedYear; private string savedMake; private string savedModel; private string savedColor; [DataMember(EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int Id { get; set; } [DataMember(EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Year { get; set; } [DataMember(EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Make { get; set; } [DataMember(EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Model { get; set; } [DataMember(EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Color { get; set; } [OnSerializing] void OnSerializing(StreamingContext ctx) { this.savedId = this.Id; this.savedYear = this.Year; this.savedMake = this.Make; this.savedModel = this.Model; this.savedColor = this.Color;
source share