DotNetCurry Logo

Serializing JSON Data into Binary Form

Posted by: Mahesh Sabnis , on 4/23/2016, in Category C#
Views: 13392
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)
        {
            //1.
            string studentData = @"{
                            'StudentId':'1',
                            'SyudentName':'MS',
                            'AcadmicYear':'First',
                            'Courses':[
                                        {'CourseId':'101','CourseName':'Compiler Design'},
                                        {'CourseId':'101','CourseName':'Compiler Design'}
                                      ]
                }";

            //2.
            var studentObject = JsonConvert.DeserializeObject(studentData);
            //3.
            JsonSerializer jsonSerializer = new JsonSerializer();
            //4.
            MemoryStream objBsonMemoryStream = new MemoryStream();
            //5.
            BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream);
            //6.
            jsonSerializer.Serialize(bsonWriterObject, studentObject);

            //7.
            Console.WriteLine(Encoding.ASCII.GetString(objBsonMemoryStream.ToArray()));
            Console.WriteLine();

            Console.WriteLine(Convert.ToBase64String(objBsonMemoryStream.ToArray()));
            Console.ReadLine();
        }
    }
}

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.

json-bson-result

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.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years 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). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




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