用于JSON解析的libcurl + rapidjson出错(null dom)

时间:2018-04-21 12:35:57

标签: c++ libcurl rapidjson

我无法通过使用rapidjson的API解析字符串(通过curl的帖子)到json

NULL DOM

String from curl's post

作为图片我已经获得了json,但我无法解析它来分析信息,因为Dom有空数据。作为初学者,我真的需要帮助,3Q~。

    int main(int argc, const char * argv[]) {
// insert code here...

rapidjson::Document doc;
doc.SetObject();    //key-value 相当与map
//doc.Setvalue();        //数组型 相当与vector
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器

doc.AddMember("answerId","1804201043079617296361988",allocator);
doc.AddMember("queryItems", true, allocator);
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);  //PrettyWriter是格式化的json,如果是Writer则是换行空格压缩后的json
//rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//doc.Accept(writer);
//std::cout<<buffer.GetString()<<std::endl;

    CURL *curl;
    CURLcode res;
    std::stringstream out;

    //HTTP报文头
    struct curl_slist* headers = NULL;

    const char *url = "https://www.qingsuyun.com/h5/actions/exam/execute/find-exam.json";

    curl = curl_easy_init();

    if(curl)
    {
        //设置url
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl,  CURLOPT_CUSTOMREQUEST, "POST");//自定义请求方式

        // 设置要POST的params
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"answerId=1804201043079617296361988&queryItems=true");

        // 设置接收数据的处理函数和存放变量
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);//设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);//设置写数据
        res = curl_easy_perform(curl);//执行

        curl_slist_free_all(headers); /* free the list again */
        string str_json = out.str();//返回请求值
        printf("%s",str_json.c_str());

        int iStart = str_json.find("{");
        int iEnd = str_json.rfind("}");
        if ((iStart < 0) || (iEnd < 1) || (iStart > iEnd))
        {
            return -1;
        }
        std::string strTemp = str_json.substr(iStart, (iEnd - iStart + 1));
        rapidjson::Document document;

        document.Parse(strTemp.c_str());
        if (document.HasParseError())
        {
            return -1;
        }
        rapidjson::Document::AllocatorType& allocator = document.GetAllocator();}
     return 0;}

0 个答案:

没有答案