Reputation: 365
I have a c++ application in Visual C++ 2013 that uses cpprestsdk to get info from server. It is working fine (an example here)
Now, I am using an external third party API and this API has a method that return an string as follows:
{"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"}}
How can I convert this string to web::json using cpprestsdk in order to iterate over "pet collection"?
Upvotes: 4
Views: 6030
Reputation: 490583
With REST SDK:
web::json::value from_string(std::string const &input) {
web::json::value ret = json::value::parse(input);
return ret;
}
You can also use the nlohmann JSON library to handle the JSON part of the task:
using json = nlohmann::json;
json parsed_data = json::parse(input);
Using the nlohmann library iterating the data becomes utterly trivial:
for (auto const &item : parsed_data["result"]["data"])
std::cout << "Name: " << item["PetName"] << "\t" <<
"ID: " << item["PetId"] << "\n";
Upvotes: 6