How to use MessagePack in C#?

允我心安 提交于 2019-12-10 13:57:38

问题


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.


回答1:


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.




回答2:


I am surprised, nobody understood what the user asked. There are so many nuget packages for msgpack and it's really confusing which one to use and how to include in the projects. Im assuming the user wanted to know how to include msgpack in the .net project just like me.

Install MessagePack for CLI from Nuget packages

and then include like this

using MsgPack.Serialization;



回答3:


I find an example at: http://www.irisclasson.com/2012/12/17/serializing-and-deserializing-packingunpacking-to-a-file-andor-memorystream-with-messagepack-in-c/ I test it in my code, and send the Byte[] data to another host by zmq. It works.




回答4:


In the latest versions of msgpack-cli the Create method as in MessagePackSerializer.Create<T>(); is marked as obsolete.

Example usage as given in the project's github page may be:

// Creates serializer.
var serializer = SerializationContext.Default.GetSerializer<T>();
// Pack obj to stream.
serializer.Pack(stream, obj);
// Unpack from stream.
var unpackedObject = serializer.Unpack(stream);



回答5:


Install the package named MsgPack from NuGet. See the pic here :



来源:https://stackoverflow.com/questions/15846355/how-to-use-messagepack-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!