如何将 cpr 的 get 响应转换为 json 对象?
How do i convert cpr's get response into a json object?
我一直在寻找一个易于理解的库,它可以在 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.text
传递给 nlohmann::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
我确实对代码进行了一些尝试,并最终弄明白了。
基本上我想做的是将 "JSON String" 转换为 JSON 对象。
我通过使用方法 nlohmann::json::parse();
实现了它
Json j = Json::parse(r.text);
string xx = j["token"];
我一直在寻找一个易于理解的库,它可以在 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.text
传递给 nlohmann::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
我确实对代码进行了一些尝试,并最终弄明白了。
基本上我想做的是将 "JSON String" 转换为 JSON 对象。
我通过使用方法 nlohmann::json::parse();
Json j = Json::parse(r.text);
string xx = j["token"];