gpt4 book ai didi

c++ - 使用 cpprestsdk 将字符串转换为 web::json

转载 作者:行者123 更新时间:2023-11-28 04:47:20 27 4
gpt4 key购买 nike

我在 Visual C++ 2013 中有一个 C++ 应用程序,它使用 cpprestsdk 从服务器获取信息。它工作正常(一个例子 here )

现在,我正在使用外部第三方 API,这个 API 有一个返回字符串的方法,如下所示:

{"result":{"data":[{"PetId":"Pet1","PetName":"Name1","PetCategory":"1"},{"PetId":"Pet2","PetName":"Name2","PetCategory":"2"},{"PetId":"Pet3","PetName":"Name3","PetCategory":"3"}],"code":"200","msg":"Operation succeeded"}}

如何使用 cpprestsdk 将此字符串转换为 web::json 以便迭代“宠物收藏”?

最佳答案

使用 REST SDK:

web::json::value from_string(std::string const &input) {    

web::json::value ret = json::value::parse(input);
return ret;
}

您还可以使用 nlohmann JSON 库来处理任务的 JSON 部分:

using json = nlohmann::json;

json parsed_data = json::parse(input);

使用 nlohmann 库迭代数据变得非常简单:

for (auto const &item : parsed_data["result"]["data"])
std::cout << "Name: " << item["PetName"] << "\t" <<
"ID: " << item["PetId"] << "\n";

关于c++ - 使用 cpprestsdk 将字符串转换为 web::json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49013426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com