0

I'm using Casablanca, cpprestsdk to consume REST APIs in C++, in Visual Studio 2015 Professional. I'm trying to develop a simple example here hitting an API and parsing the response as JSON. The URL I'm using, actually returns all the parameters sent to the API.

I've hit the API and got response as well, extracted json from the response successfully. But when i try to read a value at any key from json, it crashes. Hence i put a check whether that key is available or not, and it always says json does not have the field. As an example i printed the data i.e. json. It has the key/field "name" but when i check it via has_field, it returns false.

Please help.

Complete code is below :

 json::value postData;
 postData[L"name"] = json::value::string(L"Joe Smith");
 postData[L"sport"] = json::value::string(L"Baseball");

 http_client client(L"https://httpbin.org/post);

 http_request request(methods::POST);

 request.set_body(postData);

 client.request(request).then([](web::http::http_response response) {

  json::value j = response.extract_json().get();

  json::value data = j.at(U("data"));

  std::wcout << "Json : " << data;   
  // Prints "{\"name\":\"Joe Smith\",\"sport\":\"Baseball\"}"

  if (data.has_field(U("name"))) {
   std::cout << "Name Found";
  }
  else {
   std::cout << "Name key not Found";
  }

 });
Gurdeep
  • 171
  • 9

1 Answers1

0

It seems that your response looks like this:

{ "data": "{\"name\":\"Joe Smith\",\"sport\":\"Baseball\"}" }`

i.e. the actual data is not a JSon object but escaped JSon passed as string. I guess you need to return a payload that looks like this to do what you want to do the way you are doing it:

{
    "data": {
        "name": "John Smith", 
        "sport": "Baseball"
    }
}
Pawel
  • 31,342
  • 4
  • 73
  • 104