在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?
在上给出的示例中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>();
然后对接收到的映射进行迭代。希望能有所帮助。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象