sách gpt4 ai đã đi

curl - JSON nhanh không thành công, khẳng định `IsObject()' không thành công

In lại 作者:行者123 更新时间:2023-12-01 14:28:46 27 4
mua khóa gpt4 Nike

我正在尝试使用 RapidJSON 解析从服务器接收到的数据。以下是收到的确切字符串:

[
{
"Node": "9478149a08f9",
"Address": "172.17.0.2",
"ServiceID": "HSS",
"ServiceName": "HSS",
"ServiceTags": [],
"ServiceAddress": "",
"ServicePort": 6666,
"ServiceEnableTagOverride": false,
"CreateIndex": 2855,
"ModifyIndex": 2855
}
]

Mã như sau

int main(void)
{
CURL *curl;
CURLcode res;

struct MemoryStruct chunk;

chunk.memory = (char *)malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */

/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);

/* get a curl handle */
curl = curl_easy_init();
if(curl) {
/* First set the URL that is about to receive our POST. This URL can
just as well be a https:// URL if that is what should receive the
data. */
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8500/v1/catalog/service/HSS");
/* Now specify the POST data */

// Set the callbackfunction to handle the JSON string
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));

/* always cleanup */
curl_easy_cleanup(curl);
}

std::string str;
str.assign(chunk.memory,chunk.size);

cout<<"The string response is :"<<><>
Document d;
d.Parse(str.c_str());

assert(d.IsObject());

<-- 这里失败了

JSON 数据有效但不确定为什么仍然失败。

1 Câu trả lời

您的 JSON 字符串是数组。因此,如果您检查 IsObject(),它会失败。仔细看JSON字符串,你会发现你关心的是[],这表明它是一个数组。

取自JSON官网:

An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

试试下面的代码:

string str_json = "[{\"Node\":\"9478149a08f9\",\"Address\":\"172.17.0.2\",\"ServiceID\":\"HSS\",\"ServiceName\":\"HSS\",\"ServiceTags\":[],\"ServiceAddress\":\"\",\"ServicePort\":6666,\"ServiceEnableTagOverride\":false,\"CreateIndex\":2855,\"ModifyIndex\":2855}]";
rapidjson::Document doc;
doc.Parse(str_json.c_str());

//assert(doc.IsObject());
if(doc.IsArray()){
cout << "is array" << endl;
}
for(Value::ConstValueIterator itr = doc.Begin(); itr != doc.End(); ++itr){
const Value& obj = *itr;
for(Value::ConstMemberIterator it = obj.MemberBegin(); it != obj.MemberEnd(); ++it){
if(it->value.IsString()){
cout << it->name.GetString() << ": " << it->value.GetString() << endl;
}
// other codes...
}
}

关于curl - 快速 JSON 失败,断言 `IsObject()' 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875401/

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com