2014-07-22 1 views
2

그래서 저는 libcurl 및 jsoncpp를 사용하여 JSON을 구문 분석하는 기본 예제를 인터넷에서 살펴 보았지만 찾을 수 없었습니다.libCurl 및 JsonCpp을 사용하여 https 웹 서버에서 구문 분석

libcurl과 jsoncpp를 사용하는 간단한 예제 (여기에 .json으로 끝나는 링크 자체는 json을 직접 잡아 당길 링크)를 분석하여 json을 다운로드 할 수 있습니다. 인쇄합니다.

모든 도움을 주실 수 있습니다. 감사!

Euden는

+2

구문 분석과 JSON [** jsoncpp **] (https://github.com/open-source-parsers/jsoncpp)과와 다운로드 컨텐츠 [** libcurl에 **] (HTTP : // cu rl.haxx.se/libcurl/)는 두 가지 별개의 활동이며, 둘 다 각각의 사이트에서 상당히 문서화되어 있습니다. 그렇다면 특정 문제를 함께 묶어서 (즉, 다운로드 + 구문 분석 = 성공) 무엇입니까? – WhozCraig

+0

가능한 경우 다운로드 및 구문 분석의 간단한 예제를 원합니다. –

답변

8

여기 libcurl에 그리고 b) JsonCpp로 파싱을 통해 JSON 개체를 얻을에 독립적 인 예) HTTP이다. @WhozCraig은 이것들이 완전히 별개의 두 가지 활동이라고 말하는 것은 맞지만 두 가지를 수행하는 프로젝트가 있으므로 우연히 JSON을 가져 와서 파싱하는이 작은 샘플을 집계하여 this nifty page에서 가져 왔습니다. 당신이 main.cpp라는 파일에이 코드를 넣으면

, 당신은, 링크를 컴파일 및 실행 (가정 libcurl에와 libjsoncpp이 경로에서 사용할 수있는)와 :

g++ main.cpp -ljsoncpp -lcurl -o example.out && ./example.out

// main.cpp 
#include <cstdint> 
#include <iostream> 
#include <memory> 
#include <string> 

#include <curl/curl.h> 
#include <json/json.h> 

namespace 
{ 
    std::size_t callback(
      const char* in, 
      std::size_t size, 
      std::size_t num, 
      std::string* out) 
    { 
     const std::size_t totalBytes(size * num); 
     out->append(in, totalBytes); 
     return totalBytes; 
    } 
} 

int main() 
{ 
    const std::string url("http://date.jsontest.com/"); 

    CURL* curl = curl_easy_init(); 

    // Set remote URL. 
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); 

    // Don't bother trying IPv6, which would increase DNS resolution time. 
    curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 

    // Don't wait forever, time out after 10 seconds. 
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10); 

    // Follow HTTP redirects if necessary. 
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); 

    // Response information. 
    int httpCode(0); 
    std::unique_ptr<std::string> httpData(new std::string()); 

    // Hook up data handling function. 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); 

    // Hook up data container (will be passed as the last parameter to the 
    // callback handling function). Can be any pointer type, since it will 
    // internally be passed as a void pointer. 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, httpData.get()); 

    // Run our HTTP GET command, capture the HTTP response code, and clean up. 
    curl_easy_perform(curl); 
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); 
    curl_easy_cleanup(curl); 

    if (httpCode == 200) 
    { 
     std::cout << "\nGot successful response from " << url << std::endl; 

     // Response looks good - done using Curl now. Try to parse the results 
     // and print them out. 
     Json::Value jsonData; 
     Json::Reader jsonReader; 

     if (jsonReader.parse(*httpData, jsonData)) 
     { 
      std::cout << "Successfully parsed JSON data" << std::endl; 
      std::cout << "\nJSON data received:" << std::endl; 
      std::cout << jsonData.toStyledString() << std::endl; 

      const std::string dateString(jsonData["date"].asString()); 
      const std::size_t unixTimeMs(
        jsonData["milliseconds_since_epoch"].asUInt64()); 
      const std::string timeString(jsonData["time"].asString()); 

      std::cout << "Natively parsed:" << std::endl; 
      std::cout << "\tDate string: " << dateString << std::endl; 
      std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl; 
      std::cout << "\tTime string: " << timeString << std::endl; 
      std::cout << std::endl; 
     } 
     else 
     { 
      std::cout << "Could not parse HTTP data as JSON" << std::endl; 
      std::cout << "HTTP data was:\n" << *httpData.get() << std::endl; 
      return 1; 
     } 
    } 
    else 
    { 
     std::cout << "Couldn't GET from " << url << " - exiting" << std::endl; 
     return 1; 
    } 

    return 0; 
} 

출력 보이는 같은 :

 
Got successful response from http://date.jsontest.com/ 
Successfully parsed JSON data 

JSON data received: 
{ 
    "date" : "03-09-2015", 
    "milliseconds_since_epoch" : 1425938476314, 
    "time" : "10:01:16 PM" 
} 

Natively parsed: 
    Date string: 03-09-2015 
    Unix timeMs: 1425938476314 
    Time string: 10:01:16 PM 
관련 문제