如何将nlohmann/json的binary类型转换为std::vector<uint8_t>?
问题根因
你调试打印时看到的包含bytes、subtype字段的JSON结构,是nlohmann/json将二进制类型序列化为普通JSON文本时的兼容输出格式,运行时内存中response_json["raw_data"]的实际类型是二进制枚举值json::value_t::binary,既不是普通数组也不是JSON对象,因此你尝试的两种写法都会触发类型错误:
- 第一种写法直接将二进制类型转
std::vector<uint8_t>,库不会做隐式转换,所以报类型不匹配 - 第二种写法把二进制类型当作普通JSON对象用
[]访问字段,不符合类型要求所以报错
正确写法
直接调用get_binary()方法获取二进制封装对象,再取其内部持有的bytes成员即可,编译器会自动做返回值优化,不会产生额外的数组拷贝:
std::vector<uint8_t> unpack(std::vector<uint8_t> msg){ json response_json = json::from_msgpack(msg); return response_json["raw_data"].get_binary().bytes; }
如果需要兼容旧版本的nlohmann/json库,也可以用显式类型转换的写法:
std::vector<uint8_t> unpack(std::vector<uint8_t> msg){ json response_json = json::from_msgpack(msg); auto binary_obj = response_json["raw_data"].template get<nlohmann::json::binary_t>(); return binary_obj.bytes; }
内容的提问来源于stack exchange,提问作者Paul Würtz
相关产品推荐
相关产品推荐

