How to use MessagePack in C#?

DeepSpace101 picture DeepSpace101 · Apr 6, 2013 · Viewed 21.4k times · Source

I read the msgpack-cli quick start documentation.

I also got the C# (CLI) NuGet package (v0.3).

None of the classes (eg BoxingPacker, CompiledPacker or ObjectPacker) mentioned in the official documentation exist in the NuGet package (!!). I'm presuming the documentation has been orphaned.

So does anyone have examples how to serialize/deserialize to/from MessagePack within C#? I'm trying to do this for an object and am interested in the binary nature of the serializer.

Answer

DeepSpace101 picture DeepSpace101 · Dec 25, 2013

To future readers: I'd go with Avro or Protocol Buffers or even Thrift over MessagePack based on these results ...

For the sake of the specific question, the key portions are:

public byte[] Serialize<T>(T thisObj)
{
    var serializer = MessagePackSerializer.Create<T>();

    using (var byteStream = new MemoryStream())
    {
        serializer.Pack(byteStream, thisObj);
        return byteStream.ToArray();
    }
}

public T Deserialize<T>(byte[] bytes)
{
    var serializer = MessagePackSerializer.Create<T>();
    using (var byteStream = new MemoryStream(bytes))
    {
        return serializer.Unpack(byteStream);
    }
}

The entire R&D type project, with results is at https://github.com/sidshetye/SerializersCompare and the specific function calls are here.