c++ 使用boost::json访问嵌套JSON时出错?

kcwpcxri  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(164)

使用以下JSON:

  1. {
  2. type: "test",
  3. version: 1,
  4. data: {
  5. name: "omni",
  6. id: "123",
  7. value: 3
  8. }
  9. }

字符串
我尝试使用2个C++函数获取其数据:

  1. void process_data(std::string type, std::string data)
  2. {
  3. boost::json::value data = boost::json::parse(data);
  4. std::string name = json.at("name").as_string().c_str();
  5. std::string id = json.at("id").as_string().c_str();
  6. int value = json.at("value").as_int64();
  7. std::cout << "Message data content:" << std::endl;
  8. std::cout << "Name: " << name << std::endl;
  9. std::cout << "Id: " << id << std::endl;
  10. std::cout << "Value: " << value << std::endl;
  11. }
  12. void process_message(std::string payload)
  13. {
  14. boost::json::value json = boost::json::parse(payload);
  15. std::string type = json.at("type").as_string().c_str();
  16. int version = json.at("version").as_int64();
  17. std::cout << "Message received:" << std::endl;
  18. std::cout << "Type: " << type << std::endl;
  19. std::cout << "Version: " << version << std::endl;
  20. std::string data = json.at("data").as_string().c_str(); !!! Getting error here
  21. process_data(data);
  22. }


解析data时出现以下错误:

  1. terminate called after throwing an instance of 'boost::wrapexcept<std::invalid_argument>'
  2. what(): not a string
  3. Aborted (core dumped)


有办法解决吗?

whitzsjs

whitzsjs1#

你不能像对待字符串一样对待JSON对象。正如评论者所说,序列化它:

  1. std::string data = serialize(json.at("data"));

字符串
然而,序列化是一种反模式,除非你打算通过(文本)协议发送。相反,传递json值:

  1. process_data(json.at(“data”));


最好的部分是,它将包括类型,如果它的变量。

相关问题