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

Accessing values

Open davidglavas opened this issue 5 years ago • 4 comments
trafficstars

Is it possible to access values in a serialized message or msgpack::object?

davidglavas avatar Jan 25 '20 16:01 davidglavas

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.

redboltz avatar Jan 26 '20 05:01 redboltz

Here is document https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_visitor#visitor-interface

redboltz avatar Jan 26 '20 05:01 redboltz

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?

davidglavas avatar Jan 30 '20 14:01 davidglavas

There is no straight forward way but https://github.com/msgpack/msgpack-c/wiki/v_2_0_cpp_json might help you.

redboltz avatar Feb 11 '20 12:02 redboltz