Serializing JSON Data into Binary Form

Posted by: Mahesh Sabnis , on 4/23/2016, in Category C#
Views: 53255
Abstract: Using Netwonsoft.Json package to work with JSON Serialization and Deserialization operations

Data operations like data reading and writing are common in application development. Different clients consume different types of data. For example the data can be in a binary format, or an Xml format. But in case of Web Applications sending binary data from client-to-server may be a challenge due to its format, as well as ports that block it. XML being textual in nature, moves seamlessly across different ports. The XML form is acceptable over Binary, but the Xml data needs encoding when it is passed over HTTP. You have to escape/unescape an XML file removing traces of characters (< is replaced with &lt; & is replaced with &amp; and so on ) that could be treated as markup. This makes  data communication more complex because the size of the data message increases as a result of the encoding.


What is JSON and why to use it?

JSON is JavaScript Object Notation. The advantage of JSON is that it represents the data in human readable form and since it is in a Text form, it can easily pass through without any message encoding. Today, where web application development is reaching new heights with the next level of JavaScript frameworks and libraries, JSON is the de-facto standard for data communication. Since JSON format is supported by REST services, mobile client applications can also easily use it.

JSON is not natively supported by the .NET programming language for e.g. C#. So when we are developing applications using C#, it is important to make use of JSON.NET - a JSON framework for .NET. We can download JSON.NET from the NuGet Package Manager within Visual Studio. Open the console. "View" > "Other Windows" > "Package Manager Console". Then type the following:

Install-Package Newtonsoft.Json

What is BSON?

BSON is Binary JSON. This is a Binary format in which zero or more Key/Value pairs are stored as a single entity. This entity is called as a document. BSON supports all JSON types (objects, arrays, strings, integers, etc) and can store binary data directly. This eliminates the additional base64 encoded text size overhead that regular JSON has with binary data. Reading and writing BSON is also faster than JSON which makes it a superset of JSON. More information can be found in this link.

JSON.NET supports reading and writing binary JSON (BSON). In this article we will use Netwonsoft.Json package to work with JSON Serialization and Deserialization operations.

The Application is implemented using Visual Studio 2015, but this is supported with Visual Studio 2013 too.

Step 1: Open Visual Studio and create a new Console Application, name this as JSON_BSON. In this project, right-click and select Manage NuGet Packages, this will open the NuGet Packet Manager window. Search for Newtonsoft.Json package and install it.

Step 2: In Program.cs add the following code

using System;
using System.Text;

using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Bson;

namespace JSON_BSON
    class Program
        static void Main(string[] args)
            string studentData = @"{
                                        {'CourseId':'101','CourseName':'Compiler Design'},
                                        {'CourseId':'101','CourseName':'Compiler Design'}

            var studentObject = JsonConvert.DeserializeObject(studentData);
            JsonSerializer jsonSerializer = new JsonSerializer();
            MemoryStream objBsonMemoryStream = new MemoryStream();
            BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream);
            jsonSerializer.Serialize(bsonWriterObject, studentObject);



The above code has the following specifications.

(Note: The following line numbers match with comment numbers applied on code.)

1. Defines the string variable of name studentData. This is set to a string with JSON Schema.

2. Deserialize the studentData into JSON object form.

3. Declare an instance of JsonSerializer.

4. Since we need to represent the data in binary format we need MemoryStream object.

5. An instance of BsonWriter class. This represents a writer that provide fast, non-cached, forward-only way of generating JSON data.

6. Serialize the JSON data into BSON.

7. Print the result. We are printing data in ASCII encoding with 7-bit character set and an array of 8-bit unsigned integer with its equivalent 64-bit string encoding using Convert.ToBase64String.

Run the application and the following result will be displayed.


In this article, we saw how to serialize JSON data to Binary form. In the next set of articles, we will see more techniques as well LINQ to JSON.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!