msgpack-c
msgpack-c copied to clipboard
Add new value to object
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
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;
}
Great, thank you.