4

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"?

0

1 Answer 1

6

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.