1

我一直在寻找一个易于理解的库,可以在 C++ 中发出 HTTP REST 请求,然后我遇到了 CPR。我成功地从服务器获得了响应,但我发现很难访问返回的 JSON 对象。

API 获取请求:

auto r = cpr::Get(cpr::Url{ "https://example.net/api/token" },
        cpr::Parameters{ {"username", login}, {"password", password}, 
  {"hwid", "TestChecker"}, {"obt", "1"}});
    r.status_code;                 
    r.header["application/json"];      
    r.text;

我试图像这样传递r.textnlohmann::json j = r.text;访问我想要的特定对象string xx = j["token"]; 正如预期的那样,它抛出了一个错误。

如果有人能告诉我如何实现我未能做到的事情,我将不胜感激。

编辑:添加参考

心肺复苏术:https ://www.codeproject.com/Articles/1244632/Making-HTTP-REST-Request-in-Cplusplus

nlohmann/json:https ://github.com/nlohmann/json

4

1 回答 1

4

我确实玩弄了一些代码,终于弄明白了。基本上我想做的是将“JSON 字符串”转换为 JSON 对象。我通过使用方法实现了它nlohmann::json::parse();

Json j = Json::parse(r.text);
string xx = j["token"];
于 2019-05-15T19:38:10.743 回答