Reduce traffic by serializing JSON with different alias with Json.NET and C#

Reducing speed and increasing performance by reducing traffic with JSON size

One of the reasons JSON is used rather than XML is it's simplicity in notation. However XML is claimed to be more human readable than JSON and JSON is easier to parse for machines, so basically we switched from XML in favor to machine processing.

If you take a C# class and serialize it to JSON string you still find it quite readable since we kept all nice property names in the JSON output. Did we reduce the size of data in favor to machine reading speed? Comparing to XML, definitely but we are still using descriptive names which are only important to us, our parser does not care about it, so there is space fro improvement.

Here is a sample class in C# and it's output in JSON format. Simple serialization of Person class instance using with Json.NET

using System;
using Newtonsoft.Json;
namespace JsonOptimizationConsoleApp
{

    public class Person
    {
        public Guid Id { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String EmailAddress { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person()
            {
                Id = Guid.Parse("ed391cc44a1448709a81812d22243dd1"),
                FirstName="Dejan",
                LastName = "Stojanovic",
                EmailAddress = "me@dejanstojanovic.net"
            };

            var json = JsonConvert.SerializeObject(person);
            var deserialized = JsonConvert.DeserializeObject<Person>(json);
        }
    }
}

    

Serialized output is minified for the file size reduction reasons.

{"Id":"ed391cc4-4a14-4870-9a81-812d22243dd1","FirstName":"Dejan","LastName":"Stojanovic","EmailAddress":"me@dejanstojanovic.net"}
    

We can clearly see that our property names are too long and all that for the sake of being readable to us. When two sides of the solution, service and client application communicate we are excluded in that process so we do not need all those long names.

But wait, if we make properties single letter, the class in C# will be difficult to maintain! Right?

Well, that's wrong. Json.NET comes with support to have different JSON and C# class notation for the same data. That means we can easily map "e" from JSON to "EmailAddress" in C# class. Our output would be something like this

{"i":"ed391cc4-4a14-4870-9a81-812d22243dd1","f":"Dejan","l":"Stojanovic","e":"me@dejanstojanovic.net"}
    

Now when we compare previous JSON output and this one we clearly see that the difference is in about 21% percent less in favor of single letter notation. Imagine, you can easily reduce your REST service traffic for about 21% percent. Let's see how do we do this.

using System;
using Newtonsoft.Json;
namespace JsonOptimizationConsoleApp
{

    public class Person
    {
        [JsonProperty("i")]
        public Guid Id { get; set; }
        [JsonProperty("f")]
        public String FirstName { get; set; }
        [JsonProperty("l")]
        public String LastName { get; set; }
        [JsonProperty("e")]
        public String EmailAddress { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person()
            {
                Id = Guid.Parse("ed391cc44a1448709a81812d22243dd1"),
                FirstName="Dejan",
                LastName = "Stojanovic",
                EmailAddress = "me@dejanstojanovic.net"
            };

            var json = JsonConvert.SerializeObject(person);
            var deserialized = JsonConvert.DeserializeObject<Person>(json);
        }
    }
}

    
Note

The amount data saved with this kind of method depends on the structure of the model and can be more on less in different cases

The nice thing is we only need to decorate our model class, no other code change needs to be done and to demonstrate this we'll serialize and deserialize decorated model class Person.

Json Optimize

As you see everything is working properly as it is working without properly decoration which means you can easily optimize your current project to appy this kind of optimization.
The limitation of this approach is that both sides need to understand and map single character property and translate it to proper C# model property, which in case you share model library is straight forward.

If you still need to monitor your JSON messages exchanged between your solution components, you can still do that using preprocessor directives to wrap the property attribute in C# model class. this way you will have your properties serialized to single character in JSON only if your compilation is not Debug. This gives you flexibility to run Debug code in your development environment with full JSON message and single character on your production with Release compiled code.

using System;
using Newtonsoft.Json;
namespace JsonOptimizationConsoleApp
{

    public class Person
    {
        #if !DEBUG
        [JsonProperty("i")]
        #endif
        public Guid Id { get; set; }
        #if !DEBUG
        [JsonProperty("f")]
        #endif
        public String FirstName { get; set; }
        #if !DEBUG
        [JsonProperty("l")]
        #endif
        public String LastName { get; set; }
        #if !DEBUG
        [JsonProperty("e")]
        #endif
        public String EmailAddress { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person()
            {
                Id = Guid.Parse("ed391cc44a1448709a81812d22243dd1"),
                FirstName="Dejan",
                LastName = "Stojanovic",
                EmailAddress = "me@dejanstojanovic.net"
            };

            var json = JsonConvert.SerializeObject(person);
            var deserialized = JsonConvert.DeserializeObject<Person>(json);
        }
    }
}

    

As you can see, only model is changed, no other change is made, so this is also suitable for existing projects and solutions and it is easily applicable.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan Stojanovic is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article