DEV Community

artydev
artydev

Posted on

MessagePack serializer the alternative to JSON serializer

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.

msgpack.js
Here is a demo in JS :DEMOJS

var sourceData = {
    aaa:123,
    number2: -0.129,
    text: "Abc with Üñıçôðé and ユニコード",
    flag: true,
    list: [ 1, 2, 3 ],
    obj: { a: 1, b: "2", c: false, d: { a: 0, b: -1 } },
    time: Date.now()
};

const bytes = msgpack.serialize(sourceData);

const data = msgpack.deserialize(bytes)

Object.keys(data).forEach(k => {
  document.write(`<div class="key">${k}</div> : ${data[k]}<br />`)
})

Enter fullscreen mode Exit fullscreen mode

Here is a msgpack converter for JS : msgpack-converter

MessagePack-Csharp
Here is a demo in c# : DEMOCS

using System;

using MessagePack;

[MessagePackObject]
public class MyClass
{
    // Key attributes take a serialization index (or string name)
    // The values must be unique and versioning has to be considered as well.
    // Keys are described in later sections in more detail.
    [Key("age")]
    public int Age { get; set; }

    [Key("prenom")]
    public string FirstName { get; set; }

    [Key("nom")]
    public string LastName { get; set; }

    // All fields or properties that should not be serialized must be annotated with [IgnoreMember].
    [IgnoreMember]
    public string FullName { get { return FirstName + LastName; } }
}

public class Program
{
    public static void Main()
    {
       var mc = new MyClass
        {
            Age = 99,
            FirstName = "hoge",
            LastName = "huga",
        };

        // Call Serialize/Deserialize, that's all.
        byte[] bytes = MessagePackSerializer.Serialize(mc);
        MyClass mc2 = MessagePackSerializer.Deserialize<MyClass>(bytes);

        // You can dump MessagePack binary blobs to human readable json.
        // Using indexed keys (as opposed to string keys) will serialize to MessagePack arrays,
        // hence property names are not available.
        // [99,"hoge","huga"]
        var json = MessagePackSerializer.ConvertToJson(bytes);
        Console.WriteLine(json);
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)