Home  /  Blog  /  Documentation  /  Code Generator   /  Settings  Serialization  /  MessagePack Serialization


Introduction of MessagePack

MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. All information related to MessagePack for CLI can be found on the official website.

In this tutorial we will learn how to serialize an object to the MessagePack format, in C# with Xsd2code++. We will be using msgpack-cli package, which can be easily installed from the Visual Studio NuGet package manager, as can be seen below :

MessagePack cli package

Setup xsd2code++ for MessagePack

To serialize with MessagePack, you just have to choose it in the xsd2code options:

The first thing we will do is to generate classes from your schema with MessagePack option. For illustration purposes, we will use the schema JSON example which can be found in the introduction page of the documentation.

MessagePack serializer

The code

Now that we have our class generated, we will move to the Main code, where we will perform the MessagePack serialization of an object of that class.

Moving on to the Main code, we will start by creating an object of class PurchaseOrderType, with some arbitrary values.

PurchaseOrderType po = new PurchaseOrderType();
po.BillTo.name = "Kaila Tamara";
po.BillTo.street = "3490  Green Hill Road";
po.BillTo.zip = 72761;
po.OrderDate = DateTime.Now.ToString();

After that, we just have to invoke the SaveToFile method to save the data in MessagePack format. The specific code for MessahePack serialization is encapsulated in the class generated by xsd2code.

// Save data to json file
// Load Data from file
var poFromFile = PurchaseOrderType.LoadFromFile("c:\\temp\\po.msgpack");

To test the result of the serialization, we can use this online tool. Simply copy the bytes printed to the console and paste them on the tool. Figure 3 illustrates the result. As can be seen, we have obtained, in JSON format, the same object we serialized in the code.

messagepack encode decode