msgpack::object 的 operator<< 以恰好匹配 JSON 的人类可读格式输出 MessagePack 对象。您可以使用std::stringstream 将该输出存储在字符串中。
#include <iostream>
#include <msgpack.hpp>
#include <sstream>
unsigned char a[] = {0x82,0xa7,'c','o','m','p','a','c','t',0xc3,0xa6,'s','c','h','e','m','a',0};
int main() {
msgpack::unpacked msg;
msgpack::unpack(msg, (char*)a, sizeof(a));
msgpack::object obj = msg.get();
std::stringstream ss;
ss << obj;
std::string demo = ss.str();
std::cout << "As string: " << demo << "\n";
}
这个输出:
As string: {"compact":true,"schema":0}
为了使其正常工作,您的 msgpack::object 不应包含 JSON 中没有等效项的任何内容(例如,扩展类型)。
Reference
Implementation