2

In the example given on http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387#QuickStartforC%2B%2B-Streamingintoanarrayormap, how do I unpack the items from the array or map (when using pack_map and pack_array) in the c++ implementaton if they are not of the same type?

If they are of the same type I can do this with 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);

However, I obviously can't do this if the values are of different type.

If this is a limitation of the c++ implementation then fair enough.

Thanks

oracal
  • 835
  • 1
  • 8
  • 13

1 Answers1

4

I happened to stumble upon your question while looking myself for more msgpack information. In my case of using msgpack to serialize a map, the map is string to variant object ( object which holds different types), so modifying your example I would serialize like this:

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

Then on decode I would do:

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>();

And then iterate over the received map. Hope that helps.

Yordan Pavlov
  • 1,303
  • 2
  • 13
  • 26