Casablanca code snippets – getting and parsing JSON data

Casablanca is very easy to get started with if you’ve used PPL tasks before, and even if you haven’t it’s still fairly straightforward to use. Here’s an example showing how easy it is to make a GET request to a webserver and to extract the response as a string.

http_client client(L"http://localhost:5540/api/values");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    auto body = response.extract_string().get();		
    std::wcout << body;
  }
});

The test service I was playing with returned JSON data, and Casablanca has classes to handle JSON too.

[
   {
      "Id":1,
      "Name":"Nish",
      "Sport":"Tennis"
   },
   {
      "Id":2,
      "Name":"Andrew",
      "Sport":"Baseball"
   }
]

Here’s an example showing how the JSON data can be parsed out.

http_client client(L"http://localhost:5540/api/values");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    response.extract_json().then([](json::value jsonValue)
    {
      for(auto iterArray = jsonValue.cbegin(); iterArray != jsonValue.cend(); ++iterArray)
      {
        const json::value &arrayValue = iterArray->second;

        for(auto iterInner = arrayValue.cbegin(); iterInner != arrayValue.cend(); ++iterInner)
        {
          const json::value &propertyName = iterInner->first;
          const json::value &propertyValue = iterInner->second;

          std::wcout 
            << L"Property: " << propertyName.as_string() 
            << L", Value: " << propertyValue.to_string() 
            << std::endl;

        }		

        std::wcout << std::endl;
      }
    });
  }
});

I hope to publish more Casablanca code samples/snippets on this blog, just FYI.

Advertisements

3 thoughts on “Casablanca code snippets – getting and parsing JSON data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s