Emitting Empty Values with ASP.NET WebApi JSON

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

Sometimes you will have complex type which have many properties. Statistically in this case some of properties in some request will not be used. If you have operations which use lists in contracts it is clear that transport of none-used values will increase the traffic on the network. To take a control of that you can use like in WCF the EmitDefaultValue attribute.

If you want to prevent rendering of default (NULL) values design the class as shown below:

[DataContract]

public class AccountData

{

/// <summary>

/// The name of the user.

/// </summary>

[DataMember(EmitDefaultValue = false)]

public string UserName { get; set; }

/// <summary>

///

/// </summary>

[DataMember(EmitDefaultValue = false)]

public List<string> Roles { get; set; }

}

Following two pictures show the result of serialization. The picture on right is serialization result in default case. If you want to optimize the traffic set the emit-attribute to FALSE (picture on left).

image_thumb[5]                                                              image_thumb[3]
[DataMember(EmitDefaultValue = false)]                                               [DataMember(EmitDefaultValue = true)]
public string UserName { get; set; }                                                        public string UserName { get; set; }


Posted Feb 28 2012, 12:09 AM by Damir Dobric
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.