Как разобрать ответ libcurl в c ++? - PullRequest
0 голосов
/ 10 апреля 2020

Я новичок в cpp. Я изо всех сил пытаюсь разобрать мой ответ от API.

Я использовал следующий код для вызова REST API.

CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "type=video&u_tid=hello&n_frames=100");
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    std::cout << res << std::endl;

}

O / P:

[{"rect": {"height": 0.670796573, "k": 6, "width": 0.767148435, "x" : 0.874048531, "y": 0.884222329}}]

Я успешно получаю требуемый ответ. Я хочу разобрать элемент как json объект.

т.е. python эквивалентный код res[0]["rect"]["height"]

Я смотрю на тип данных переменной, которую он говорит,

8CURLcode

Я также не могу разобрать, как это

std::cout << res[0] << '\n';

Как проанализировать мой ответ в c ++? любая помощь будет заметна.

РЕДАКТИРОВАТЬ-1:

Как многие из вас упоминали, используйте json lib, я перешел по этой ссылке.

Мой обновленный код:

#include <iostream>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>
#include <jsoncpp/json/value.h>
#include <curl/curl.h>

#include <typeinfo>


using namespace std;


static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main()
{
    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "type=video&u_tid=hello&n_frames=100");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        std::cout << readBuffer << std::endl;
    }


    Json::Value root;   
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( readBuffer.c_str(), root );     //parse process
    cout<<parsingSuccessful;
    if ( !parsingSuccessful )
    {
        std::cout  << "Failed to parse"<< reader.getFormattedErrorMessages();

    }
    else
    {
        std::cout << root.get("mykey", "A Default Value if not exists" ).asString() << std::endl;
    }

    return 0;
}

Ошибка:

/tmp/ccXxEiWg.o: In function `main':
json.cpp:(.text+0x155): undefined reference to `Json::Value::Value(Json::ValueType)'
json.cpp:(.text+0x164): undefined reference to `Json::Reader::Reader()'
json.cpp:(.text+0x1c0): undefined reference to `Json::Reader::parse(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Json::Value&, bool)'
json.cpp:(.text+0x21e): undefined reference to `Json::Reader::getFormattedErrorMessages[abi:cxx11]() const'
json.cpp:(.text+0x26a): undefined reference to `Json::Value::Value(char const*)'
json.cpp:(.text+0x28f): undefined reference to `Json::Value::get(char const*, Json::Value const&) const'
json.cpp:(.text+0x2a8): undefined reference to `Json::Value::asString[abi:cxx11]() const'
json.cpp:(.text+0x2e7): undefined reference to `Json::Value::~Value()'
json.cpp:(.text+0x2f6): undefined reference to `Json::Value::~Value()'
json.cpp:(.text+0x319): undefined reference to `Json::Value::~Value()'
json.cpp:(.text+0x3a4): undefined reference to `Json::Value::~Value()'
json.cpp:(.text+0x3b8): undefined reference to `Json::Value::~Value()'
/tmp/ccXxEiWg.o:json.cpp:(.text+0x3e0): more undefined references to `Json::Value::~Value()' follow
collect2: error: ld returned 1 exit status
...