msgpack-c
msgpack-c copied to clipboard
Accessing values
Is it possible to access values in a serialized message or msgpack::object?
Yes, you can read only access to msgpack::object using visitor interface.
This is json stringize visitor for msgpack::object.
https://github.com/msgpack/msgpack-c/blob/419877cf3a9d0d7a332cf9cc768c8813c019e00d/include/msgpack/v1/object.hpp#L396
And this is applying the visitor code: https://github.com/msgpack/msgpack-c/blob/419877cf3a9d0d7a332cf9cc768c8813c019e00d/include/msgpack/v1/object.hpp#L1229
You can define and apply your own visitor to msgpack::object.
Here is document https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_visitor#visitor-interface
I'm trying to perform the following 3 operations:
- serialize a plaintext json document (plaintext json -> msgpack)
- access values in the msgpack document
- deserialize a msgpack document (msgpack -> plaintext json)
For example:
#include <iostream>
#include <string>
int main(int, char**) {
// valid plaintext JSON document
std::string testJSON = "{ \"id\" : { \"numID\" : 12345, \"strID\" : \"onetwothreefourfive\", \"doubleID\" : 1.2345}, \"hello\" : \"world\", \"age\" : 42, \"cats\" : [ \"first cat\", \"second cat\", \"third cat\" ] }";
// TODO somehow use msgpack functions to perform the 3 operations:
// 1. Serialize
msgpackObject serializedDoc = msgpack.serialize(testJSON);
// 2. Access values
// access the top-level value associated with key "age" (42 in this case)
int age = serializedDoc.accessValue("age");
// 3. Deserialize
std::string originalJSON = msgpack.deserialize(serializedDoc);
std::cout << originalJson << std::endl;
}
Is there a straightforward way to do these 3 operations?
There is no straight forward way but https://github.com/msgpack/msgpack-c/wiki/v_2_0_cpp_json might help you.