在msgpack的c++实现中,如何在使用pack_map或pack_array对对象进行串行化后将其反串行化

How to de-serialise the objects back after serialising them with pack_map or pack_array, in the c++ implementation of msgpack?

本文关键字:pack 对象 msgpack 反串 array 实现 map c++      更新时间:2023-10-16

在上给出的示例中http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387#QuickStartforC%2B%2B-流式传输到anarayormap,如果c++实现中的数组或映射(当使用pack_map和pack_array时)中的项不属于同一类型,我如何解压缩它们?

如果它们是相同的类型,我可以使用pack_map:

msgpack::sbuffer buffer;
msgpack::packer<msgpack::sbuffer> pk(&buffer);
pk.pack_map(2);
pk.pack(std::string("string"));
pk.pack(std::string("hello"));
pk.pack(std::string("vector"));
pk.pack(std::string("map"));
msgpack::unpacker pac;
pac.reserve_buffer(buffer.size());
memcpy(pac.buffer(), buffer.data(), buffer.size());
pac.buffer_consumed(buffer.size());
// deserialize it.
msgpack::unpacked msg;
pac.next(&msg);
msgpack::object obj = msg.get();
std::map<std::string, std::string> resultMap;
obj.convert(&resultMap);

然而,如果值的类型不同,我显然无法做到这一点。

如果这是c++实现的一个限制,那么就足够公平了。

感谢

我在查找更多消息包信息时偶然发现了你的问题。在我使用msgpack序列化映射的情况下,映射是字符串到变量对象(包含不同类型的对象),因此修改您的示例时,我会这样序列化:

pk.pack_map(2);
pk.pack(std::string("string"));
pk.pack(std::string("hello"));
pk.pack(std::string("vector"));
pk.pack(1); // NOTE integer here

然后在解码时我会做:

typedef std::map<std::string, msgpack::object> MapStrMsgPackObj;
// deserialize it.
msgpack::unpacked msg;
pac.next(&msg);
msgpack::object obj = msg.get();
MapStrMsgPackObj mmap = obj.as<MapStrMsgPackObj>();

然后对接收到的映射进行迭代。希望能有所帮助。