我在JSON对象中有数据,我似乎无法访问。
错误:
> testGetprice3.o: testGetprice3.cpp:71: int getData(): Assertion > `document["success"].IsString()' failed.
我试过切换数据类型,它只是错误。 如何正确访问我的JSON对象数据?
#include "rapidjson/include/rapidjson/document.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <curl/curl.h>
#include <unistd.h>
#include <unordered_map>
#include <string>
using namespace rapidjson;
struct myData
{
std::fstream *file;
std::string *str;
};
size_t write_data(void *ptr, size_t size, size_t nmemb, myData *data)
{
size_t numBytes = size * nmemb;
if (data->file)
data->file->write((char*)ptr, numBytes);
if (data->str)
*data->str += std::string((char*)ptr, numBytes);
return numBytes;
}
//function to get coin data and perform analysis
int getData()
{
int count = 0;
//begin non terminating loop
while(true)
{
count++;
CURL *curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=155");
std::fstream file("/home/coinz/cryptsy/myfile.txt", std::ios_base::out | std::ios_base::ate);
std::string json;
myData data;
data.file = &file;
data.str = &json;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
/* Perform the request, res will get the return code */
CURLcode res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
{
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else
{
file << std::endl;
//begin deserialization
Document document;
document.Parse(json.c_str());
assert(document.HasMember("success"));
assert(document["success"].IsString());
//std::cout << "The Last Traded Price is = " << document["lasttradeprice"].GetString() << std::endl;
}
/* always cleanup */
curl_easy_cleanup(curl);
}
//timer for URL request. *ADUJST ME AS DESIRED*
usleep(10000000);
}
return 0;
}
//Le Main
int main(void)
{
getData();
}
答案 0 :(得分:0)
您声明已更改数据类型,但未说明您尝试过哪些数据类型。从您使用的网址中,成功将返回"success":1
,即int
。
变化:
assert(document["success"].IsString());
为:
assert(document["success"].IsInt());
答案 1 :(得分:0)
查看您的JSON数据,success
成员是一个int(因为它没有引号括起来)。
有关JSON类型的更多信息,请访问:http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example
如果success
成员是字符串,则JSON数据如下所示:{"success":"1",...
因此,当您调用assert(document["success"].IsString())
时会导致错误,因为success
成员不是字符串,而是int。
由于success
成员是一个int,因此更改断言以测试它是否为int - assert(document["success"].IsInt())