在C語言中,獲取JSON數(shù)據(jù)是一項(xiàng)常見的任務(wù)。雖然C語言并沒有內(nèi)置的JSON解析庫,但我們可以使用C POST方法來獲取JSON數(shù)據(jù)。下面是一個獲取JSON數(shù)據(jù)的代碼示例:
#include <stdlib.h> #include <stdio.h> #include <curl/curl.h> typedef struct { char *data; size_t size; } MemoryStruct; static size_t writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; MemoryStruct *mem = (MemoryStruct *) userp; char *ptr = realloc(mem->data, mem->size + realsize + 1); if (ptr == NULL) { printf("not enough memory\n"); return 0; } mem->data = ptr; memcpy(&(mem->data[mem->size]), contents, realsize); mem->size += realsize; mem->data[mem->size] = 0; return realsize; } int main(int argc, char **argv) { CURL *curl; CURLcode res; MemoryStruct chunk; chunk.data = (char *) malloc(1); chunk.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api/getjsondata"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &chunk); res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved\n", (long) chunk.size); printf("JSON data: %s\n", chunk.data); } curl_easy_cleanup(curl); } free(chunk.data); curl_global_cleanup(); return 0; }
在這個代碼中,我們使用了CURL庫來處理HTTP請求和響應(yīng),通過POST請求獲取了JSON數(shù)據(jù)。在main函數(shù)中,我們定義了一個MemoryStruct結(jié)構(gòu)體來存放獲取到的JSON數(shù)據(jù),通過writeMemoryCallback函數(shù)來將數(shù)據(jù)寫入到MemoryStruct中。最后,我們使用curl_easy_perform函數(shù)來執(zhí)行HTTP請求并獲取響應(yīng)數(shù)據(jù),通過chunk.data輸出JSON數(shù)據(jù)。
下一篇vue 2.4