msgpack-c icon indicating copy to clipboard operation
msgpack-c copied to clipboard

Add new value to object

Open xiaoxiangdu opened this issue 11 years ago • 2 comments

Hi guy,

After I pack some thing to the buffer, then unpack it. Can I add new values to the unpacked object? I do not get a example of this usage.

Best, Mack

xiaoxiangdu avatar Jan 14 '15 04:01 xiaoxiangdu

Unfortunately, there is no way to add the new values to msgpack::object.

You need to convert msgpack::object to some type. Then add new values to the converted type instance. Finally, you can convert the converted type instance to msgpack::object.

// C++11

#include <msgpack.hpp>
#include <vector>
#include <sstream>

#include <iostream>
#include <cassert>

int main() {
    std::vector<int> v { 1, 2, 3};
    std::stringstream ss;
    msgpack::pack(ss, v);
    msgpack::unpacked u = msgpack::unpack(ss.str().data(), ss.str().size());
    msgpack::object obj = u.get();
    std::cout << obj << std::endl;

    // There is no way to add elements to obj directory.

    // You can add elements to coverted type.
    std::vector<int> updated = obj.as<std::vector<int>>();
    updated.push_back(4);

    // Then, you can create new msgpack::object
    msgpack::zone z;
    msgpack::object updated_obj = msgpack::object(updated, z);
    std::cout << updated_obj << std::endl;
}

redboltz avatar Jan 14 '15 13:01 redboltz

Great, thank you.

xiaoxiangdu avatar Jan 15 '15 01:01 xiaoxiangdu