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 in figure 1.

MessagePack cli package

Figure 1 – Installing the MsgPack.Cli package from the NuGet package manager.

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(); = "Kaila Tamara";
po.BillTo.street = "3490  Green Hill Road"; = 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 mspack-lite tool . Simply copy the bytes printed to the console and paste them on the tool. As can be seen, we have obtained, in JSON format, the same object we serialized in the code.

messagepack encode decode

Terms & privacy

Terms of uses · Privacy policy 


CodeNGine Technologies, 19 Avenue, de la gare, 34770 Gigean, France. SIRET: 85257252800010, VAT : FR 62852572528

About the company

CodeNGine Technologies is software company based in the South of France that provides an advanced productivity code generation tool to developers using XML and JSON

Copyright © 2021 CodeNGine Technologies