Json.NET - Reducing the Payload of Data Transferred

While developing web apps, it's the duty of we, developers to make sure that we are sending only the required data back and forth. Otherwise it can cause a performance hit for for your application. Let's assume that you hava class that contains a lot of properties and in a page you are using a couple for properties in that instance for showing the data in the page. In this case if we send the whole instance to client, we are actually sending lot of unwanted data to the client consuming bandwidth and also making the page slower.

Json.net has got lot of options baked into the framework to get through these kind of situations. Json.Net will serialize all the properties and fields from the class to create the json. You can restrict that in two ways

1. JsonIgnore Attribute

If you want Json.net to ignore some properties while writing to JSON, you can decorate that property with JsonIgnore attribute as shown below.

You can see that in the example, for the property RGBValue I have decorated it with [JsonIgnore] attribute, so that it will be skipped while writing the JSON. 

2. DataMember Attribute

JsonIgnore attribute will be helpful if and only if you need to add this to a ver few of them. But this job will become very tedious if we have to decorate a lot of them. So Json.NET has got the DataMember attribute which helps us specify which all properties needs to take part in serialization.  For that first you need to decorate your class with [DataContract] attribute and the properties with [DataMember] attribute.

using System;
using Newtonsoft.Json;
using System.Runtime.Serialization;

					

public class Program
{
	public static void Main()
	{

		
		
		JsonSerializerSettings  ser = new JsonSerializerSettings ();
        
		var intObj = new ColorInfo() { ColorId=2, ColorName="Red",EffectiveDate = DateTime.MinValue, ColorCode=20 , RGBValue ="205-92-92"};
		
		var strOut = JsonConvert.SerializeObject(intObj,ser);
		Console.WriteLine(strOut);
		
	}
	[DataContract]
	public class ColorInfo
	{
		public int ColorId {get;set;}
		[DataMember]
		public string ColorName{get;set;}
		public DateTime EffectiveDate{get;set;}
	
		public string RGBValue { get;set; }
	    public int ColorCode{get;set;}
	}
}

Output 

{"ColorName":"Red"}

3. Formatting

Most probably we have enabled the formatting during development to get the json text in a readable format. But that contains a lot of whitespace which is again increasing the payload. So you need to make sure that, once you deploys to the production you need to turn it off by setting the formatting option in JsonSerializerSettings to Formatting.None.


No Comments

Add a Comment