【问题标题】:How to de-serialise the objects back after serialising them with pack_map or pack_array, in the c++ implementation of msgpack?在 msgpack 的 c++ 实现中,如何在使用 pack_map 或 pack_array 序列化对象后将对象反序列化?
【发布时间】:2013-06-23 14:14:25
【问题描述】:

http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387#QuickStartforC%2B%2B-Streamingintoanarrayormap 上给出的示例中,如果它们不是同一类型,我如何在 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++ 实现的限制,那么就足够了。

谢谢

【问题讨论】:

    标签: c++ msgpack


    【解决方案1】:

    我在寻找更多 msgpack 信息时偶然发现了您的问题。在我使用 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>();
    

    然后遍历接收到的地图。希望对您有所帮助。

    【讨论】:

    • 为什么不支持std::unordered_map?
    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多