Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Last active August 5, 2020 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosminpopescu14/75c90cb59a6623b039ac652d3f313ba2 to your computer and use it in GitHub Desktop.
Save cosminpopescu14/75c90cb59a6623b039ac652d3f313ba2 to your computer and use it in GitHub Desktop.
// JsonApi.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "curl/curl.h"
#include "JsonApi.h"
#include "json.hpp"
using namespace std;
// for convenience
using json = nlohmann::json;
int main()
{
CallApi();
}
/*
Because curl resturn a curl resource, this is to accumulate in a string the response.
It is used as a callback.
*/
size_t WriteCallback(char* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
void ProcessJson(json json)
{
int completed = 0;
int notCompleted = 0;
//C++ 11 supports for like in c# and java
for (auto it : json)
{
// "it" is of type json::reference and has no key() member
// std::cout << "value: " << it["completed"] << '\n';
if (it["completed"] == true)
{
completed++;
}
if (it["completed"] == false)
{
notCompleted++;
}
// notCompleted = it.size() - completed; not working as expected
}
cout << "Completed TODOs: " << completed << "\n";
cout << "Not completed TODOs: " << notCompleted << "\n";
}
int CallApi()
{
auto url = "https://jsonplaceholder.typicode.com/todos";
CURL* req = curl_easy_init();
CURLcode res;
std::string readBuffer;
if (req)
{
curl_easy_setopt(req, CURLOPT_URL, url);
curl_easy_setopt(req, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(req, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(req, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(req);
if (res != CURLE_OK)
{
fprintf(stderr, "curl_easy_operation() failed : %s\n", curl_easy_strerror(res));
}
auto j = json::parse(readBuffer);
ProcessJson(j);
}
curl_easy_cleanup(req);
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
#pragma once
int CallApi();
@cosminpopescu14
Copy link
Author

Completed TODOs: 90
Not completed TODOs: 110
Press any key to continue . . .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment